<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Custom\CustomController;
use App\Http\Controllers\Fee\FeeTypeController;
use App\Http\Validate\Order\Saleorder;
use App\Http\Validate\Order\Saleorderfee;
use App\Http\Validate\Order\Saleordersub;
use App\Models\Custom\Custom;
use App\Models\Balance\Balance as Balance;
use App\Models\Custom\Custom as ModelCustom;
use App\Models\Fee\FeeType;
use App\Models\Order\Outboundordersub;
use App\Models\Order\Saleorderinvoice;
use App\Models\Order\SaleorderOtherfeePay;
use App\Models\Order\SaleorderOtherfeePayApprove;
use App\Models\Order\Salesordersub;
use App\Models\Purchase\ExpenseVoucherInfoPay;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchaseOrderProcessSub;
use App\Models\Purchase\PurchaseOrderSub;
use App\Models\Saleprice\Saleprice as ModelSaleprice;
use App\Models\Settle\SettleCompany;
use App\Models\Stock\Stock as ModelStock;
use App\Models\Stock\StockSub;
use App\Models\Systemparam\Systemparam as ModelSystemparam;
use App\Models\Template\TemplateContractsStamp;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\SnCode;
use App\Services\Common\TableExtFeild;
use Illuminate\Http\Request;
use App\Models\Order\Saleorder as ModelSaleorder;
use App\Models\Order\Saleordersub as ModelSaleordersub;
use App\Models\Order\Saleorderfee as ModelSaleorderfee;
use App\Models\Order\Salesorder as ModelSalesorder;
use App\Models\Order\Saleimplementation;
use App\Models\Order\Saleimplementationsub;
use App\Models\Purchase\PurchasePayOrderApprove;
use App\Models\Refund\CustomRefund;
use App\Models\Common\EditLog;
use Illuminate\Support\Facades\DB;
use App\Models\Order\Returnordersub;
use App\Models\Stock\Stock;
use Illuminate\Support\Facades\Log;
use App\Models\Purchase\PurchaseWarehousingOrder;
use PHPUnit\Util\Exception;

/**
 * 销售订单
 */
class SaleorderController extends BaseController
{
    /***
     *  自定义的销售场景，获取订单审核状态
     *
     */
    public static $saleOrderNode = [
        'sale_order_edit' => '销售订单编辑',
        'sale_order_delivery' => '销售发货',
    ];

    /**
     * 获取表头
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new ModelSaleorder())->getTable(), $cpid);
        $subextfield = TableExtFeild::getFeildTitle((new ModelSaleordersub())->getTable(), $cpid);
        return response()->json([
            'code' => '000',
            'msg' => '获取成功',
            'data' => [
                'mainextfield' => $mainextfield,
                'subextfield' => $subextfield
            ]
        ]);
    }
    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = ModelSaleorder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $suborderinfo = ModelSaleordersub::where(['p_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->first();
        $data = TableExtFeild::getTableFeildData($request);
        if ($suborderinfo) {
            ModelSaleordersub::where(['p_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->update($data);
        } else {
            ModelSaleorder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update($data);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     *
     *  以上规则仅适用 添加
     *  1、销售订单的常规订单、锁量不锁规格、保价订单和后结算都存在自采的情况
     *  2、锁量不锁规格的订单：品名和重量，规格（30*30*16~60）必填，规格是一个区间，
     *    品名、规格是在钢材档案里面维护的，进行选择，没有库存时也可以销售，价格按照创建订单的基价计算，
     *    单价不低于基价(基价+加价)，金额=重量*单价，这里的计提和业绩按照没有加价来计算，在生成销货单时需补全其他的信息，
     *    和常规订单相同，取相应规则的加价来计算计提和业绩
     *
     *    锁量不锁规格，1.创建订单时，单价不低于基价(基价+加价)[根据取价规则]
     *                2. 发货时，按照实际钢材的基价(基价+加价),计算价格
     *
     *    -----------2025.05.07-----------
     *    数据审核，低于指导价审核（不包括订单审核），是否先扣库存/先生成执行表，审核拒绝后，动作回滚。还是审核通过后，在执行操作，
     *    目前 先扣库存，审核通过后才生成执行表
     *
     *    点价订单(后结算模式)，扣库存 需要操盘审核通过后
     *
     *    -----------2025.08.06-----------
     *   其他费用改为非必填
     *   挪到后置的发货单必填 保留现在的逻辑可以新增多个其他费用，要重新计算
     */
    public function dopostadd(Request $request)
    {
        //校验订单参数
        $params = [
            'document_date',
            'bill_type',
            'business_type',
            'custom_id',
            'custom_level',
            'custom_name',
            'settlement_company',
            'extra_type',
            'order_type',
            'wagon_number',
            'driver_phone_number',
            'purchase_manger_id',
            'purchase_manger_name',
            'suborder',
            'remark'
        ];
        $req_data = $request->only($params);
        $validate = new Saleorder('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? 0;

        $suborder = is_array($req_data['suborder']) ? $req_data['suborder'] : json_decode($req_data['suborder'], true);
        if (!$suborder) {
            return response()->json(['code' => '001', 'msg' => '请添加子订单']);
        }

        $price_data = $this->getsaleprice();
        if (isset($price_data['base']['基价'])) {
            $base_price = $price_data['base']['基价']['amount'];
        } else {
            return response()->json(['code' => '001', 'msg' => '基价不能为空']);
        }

        $custom = Custom::where('id', $req_data['custom_id'])->first();
        if (!$custom) {
            return response()->json(['code' => '001', 'msg' => '客户不存在']);
        }
        $custom = $custom->toArray();

        //------低于指导价判断使用------
        $preferential_price = $custom['preferential_price'];
        $otherfeetotal_cent = 0;
        //------低于指导价判断使用------

        $saleWeightIsSys = $saleAmountIsSys = $salePiecesIsSys = $saleWeightIsNotSys = $saleAmountIsNotSys = $salePiecesIsNotSys = 0;

        $subvalidate = new Saleordersub('add');
        $examine_status = config('constants.examine_status.normal');
        $is_sys_purchase = 1;

//        $one = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'company_costs'])->first();
//        if ($one) {
//            $companycosts = $one->value;
//        } else {
//            $companycosts = 10;
//        }

        $dataSubIsSysItem = $dataSubIsNotSysItem = [];

        $total_weight = 0;
        $order_status = config('constants.order_status.audit');//订单审核状态
        foreach ($suborder as $item) {
            if (!$subvalidate->check($item)) {
                return response()->json(['code' => '001', 'msg' => $subvalidate->getError()]);
            }
            if (empty($item['pieces'])) {
                $pieces = 0;
            } else {
                $pieces = $item['pieces'];
            }
            $stock = Stock::where(['id' => $item['stock_id']])->first();
            if (!$stock) {
                return response()->json(['code' => '001', 'msg' => '库存不存在']);
            }
            if ($stock->archive_type != 4) {
                if ($pieces <= 0) {
                    return response()->json(['code' => '001', 'msg' => '件数不能小于0']);
                }
            }
            if ($item['is_sys_purchase'] == 1 && !in_array($item["archive_type"], ['4'])) {
                if ($stock) {
                    $stock = $stock->toArray();
                    if ($stock['can_use_pieces'] < $pieces) {
                        return response()->json(['code' => '001', 'msg' => '库存不足']);
                    }
                } else {
                    return response()->json(['code' => '001', 'msg' => '库存不足']);
                }
            }

            $unit_price = mathfuncmoney('mul', $item['unit_price'], 100);
            $total_weight_g = mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
            /***
             *  检查子订单数据，是否合法
             *
             */
            $res_check_suborder_item = $this->checkSubOrderItem('SaleOrder', $req_data, $item, $total_weight_g, $unit_price, $pieces);
            if ($res_check_suborder_item['code'] != '000') {
                return response()->json($res_check_suborder_item);
            }

            $guiding_price = $base_price;
            //按照 销售订单日期加价规则时
            if ($req_data['extra_type'] == 1) {
                // 1 常规类型 3保价订单
                if (in_array($req_data['order_type'], ['1', '2', '3'])) {
                    $guiding_price = $this->getsteelprice($price_data, $base_price, $item);
                }
            }


            /***
             * 检查低于指导价审核
             *
             * 增加锁量不锁规格订单 单价检查，2025.04.25
             *
             */

            $res_guide_price = $this->checkLowGuidePrice($req_data, $custom, 'add', $unit_price, $guiding_price, $preferential_price, $item['is_sys_purchase'], $otherfeetotal_cent);
            if ($res_guide_price['code'] != '000') {
                return response()->json($res_guide_price);
            } else {
                $sub_examine_status = $res_guide_price['data']['sub_examine_status'];
            }

            /***
             *  检查每个子订单
             *
             */
            $order_review = $this->checkOrderReview($req_data, 'add');
            if ($order_review['code'] != '000') {
                return response()->json($order_review);
            } else {
                if ($order_status == config('constants.order_status.audit')) {
                    $order_status = $order_review['data']['order_status'];
                }
            }

            // if ($req_data['order_type'] != 2) {
            //     if ($item['is_sys_purchase'] == 2) {
            //         $is_sys_purchase = 2;
            //     } else {
            //         $accrual = $unit_price - $guiding_price + $companycosts;
            //         $performance = ($accrual + $otherfeetotal) * mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
            //     }
            // } else {
            //     $accrual = $unit_price - $base_price + $companycosts;
            //     $performance = ($accrual + $otherfeetotal) * mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
            // }

            // if ($req_data['order_type'] != 2) {
            //     if ($item['is_sys_purchase'] == 2) {
            //         $is_sys_purchase = 2;
            //     } else {
            //         $accrual = $unit_price - $guiding_price + $companycosts;
            //         $a = $accrual + $otherfeetotal;
            //         // $b = mathfuncweight('div', $item['total_weight'] ?? 0, 10000, 4);
            //         $b = $item['total_weight'] ?? 0;
            //         $performance = $accrual * $b;
            //         Log::info('计提:' . $accrual);
            //         Log::info('业绩:' . $performance . ';金额,' . $a . ';重量:' . $b);
            //     }
            // } else {
            //     $accrual = $unit_price - $base_price + $companycosts;
            //     $accrual = $unit_price - $guiding_price + $companycosts;
            //     $a = $accrual + $otherfeetotal;
            //     // $b = mathfuncweight('div', $item['total_weight'] ?? 0, 10000, 4);
            //     $b = $item['total_weight'] ?? 0;
            //     $performance = $accrual * $b;
            //     Log::info('计提:' . $accrual);
            //     Log::info('业绩:' . $performance . ';金额,' . $a . ';重量:' . $b);
            // }

            $subItem = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'stock_id' => $item['stock_id'] ?? 0,
                'material_id' => $item['material_id'] ?? 0,
                'archive_no' => $item['archive_no'] ?? '',
                'warehouse_name' => $item['warehouse_name'] ?? '',
                'steel_factory_name' => $item['steel_factory_name'] ?? '',
                'archive_type' => $item['archive_type'] ?? 0,
                'archive_name' => $item['archive_name'] ?? '',
                'archive_spec' => $item['archive_spec'] ?? '',
                'archive_material' => $item['archive_material'] ?? '',
                'breed_name' => $item['breed_name'] ?? '',
                'weight' => mathfuncweight('mul', $item['weight'] ?? 0, 10000),
                'total_weight' => mathfuncweight('mul', $item['total_weight'] ?? 0, 10000),
                'pieces' => $pieces ?? 0,
                'length' => $item['length'] ?? 0,
                'unit_price' => $unit_price ?? 0,
                'total' => mathfuncmoney('mul', $item['total'] ?? 0, 100),
                'guiding_price' => $guiding_price ?? 0,
                'accrual' => mathfuncmoney('mul', $item['accrual'] ?? 0, 100),
                'performance' => mathfuncmoney('mul', $item['performance'] ?? 0, 100),
                'examine_status' => $sub_examine_status ?? 1,
                'is_sys_purchase' => $item['is_sys_purchase'],
                'code' => $item['code'] ?? '',
                //'remark' => $req_data['remark'],
                'remark' => $item['remark'] ?? '',
                'create_at' => time(),
            ];
            if ($item['is_sys_purchase'] == 2) {
                $dataSubIsSysItem[] = $subItem;
            } else {
                $dataSubIsNotSysItem[] = $subItem;
            }

            if ($sub_examine_status == config('constants.examine_status.normal')) {
                if ($item['is_sys_purchase'] == 2) {
                    $saleWeightIsSys = $saleWeightIsSys + mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
                    $saleAmountIsSys = $saleAmountIsSys + mathfuncmoney('mul', $item['total'] ?? 0, 100);
                    $salePiecesIsSys = $salePiecesIsSys + $pieces;
                } else {
                    $saleWeightIsNotSys = $saleWeightIsNotSys + mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
                    $saleAmountIsNotSys = $saleAmountIsNotSys + mathfuncmoney('mul', $item['total'] ?? 0, 100);
                    $salePiecesIsNotSys = $salePiecesIsNotSys + $pieces;
                }
            }

//            $data_sub_purchase[] = [
//                'cpid' => $cpid,
//                'count' => $pieces ?? 0,
//                'weight' => mathfuncweight('mul', $item['weight'] ?? 0, 10000),
//                'total_weight' => mathfuncweight('mul', $item['total_weight'] ?? 0, 10000),
//                'stock_id' => $item['stock_id'] ?? 0,
//                'warehouse_name' => $item['warehouse_name'] ?? '',
//                'archive_no' => $item['archive_no'] ?? '',
//                'archive_name' => $item['archive_name'] ?? '',
//                'archive_spec' => $item['archive_spec'] ?? '',
//                'archive_material' => $item['archive_material'] ?? '',
//                'steel_factory_name' => $item['steel_factory_name'] ?? '',
//                'breed_name' => $item['breed_name'] ?? '',
//                'archive_type' => $item['archive_type'] ?? 0,
//                'sale_price' => $guiding_price ?? 0,
//                'sale_total_money' => mathfuncmoney('mul', $item['total'] ?? 0, 100) ?? 0,
//                'code' => $item['code'] ?? 'default',
//                'create_at' => time(),
//            ];

            $total_weight = $total_weight + mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
        }

        //增加验证, 操盘下 所有订单是否超重
        $is_over_weight = $this->checkSaleOrderOverWeight($cpid, $total_weight);
        if ($is_over_weight["code"] != '000') {
            return response()->json($is_over_weight);
        }

        // $document_number = SnCode::getSnCode('XS_');
        $buildSaleOrderNumber = $this->buildSaleOrderNumber($cpid);
        if($buildSaleOrderNumber['code'] == '001'){
            return response()->json($buildSaleOrderNumber['msg']);
        }else{
            $order_number = $buildSaleOrderNumber['order_number'];
        }

        $balance = Balance::where(['custom_id' => $req_data['custom_id']])->first()->toArray();

        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'manger_name' => $manger_name,
            'purchase_manger_id' => !empty($req_data['purchase_manger_id']) ? $req_data['purchase_manger_id'] : 0,
            'purchase_manger_name' => !empty($req_data['purchase_manger_name']) ? $req_data['purchase_manger_name'] : '',
            'order_number' => $order_number,
            // 'document_number' => $document_number,
            'document_date' => $req_data['document_date'],
            'bill_type' => $req_data['bill_type'],
            'business_type' => $req_data['business_type'],
            'custom_id' => $req_data['custom_id'],
            'custom_level' => $req_data['custom_level'],
            'custom_name' => $req_data['custom_name'],
            'custom_balace' => $balance['balance'],
            'settlement_company' => $req_data['settlement_company'],
            'extra_type' => $req_data['extra_type'],
            'order_type' => $req_data['order_type'],
            'wagon_number' => $req_data['wagon_number'] ?? '',
            'driver_phone_number' => $req_data['driver_phone_number'] ?? '',
            'examine_status' => $examine_status ?? 1,//需要用子订单状态判断
            'order_status' => $order_status,
            'is_sys_purchase' => $is_sys_purchase,
            'remark' => $req_data['remark'],
            'create_at' => time(),
            'statistics_at' => time(),
        ];

        $data_im = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'manger_name' => $manger_name,
            'order_number' => $order_number,
            'document_date' => $req_data['document_date'],
            'custom_id' => $req_data['custom_id'],
            'custom_name' => $req_data['custom_name'],
            'settlement_company' => $req_data['settlement_company'] ?? '',
            'create_at' => time(),
        ];

//        $dataPurchase = [
//            'cpid' => $cpid,
//            'sale_order_number' => $order_number,
//            'manger_id' => !empty($req_data['purchase_manger_id']) ? $req_data['purchase_manger_id'] : 0,
//            'pa_type' => 4,
//            'sales_manger_id' => $manger_id,
//            'sales_manger_name' => $manger_name,
//            'create_manger_id' => $manger_id,
//            'order_date' => time(),
//            'is_band' => 2,
//            'is_from_sale' => 2,
//            'is_completion' => 2,
//            'create_at' => time(),
//        ];
//
//        $dataPurchaseIm = [
//            'cpid' => $cpid,
//            'manger_id' => !empty($req_data['purchase_manger_id']) ? $req_data['purchase_manger_id'] : 0,
//            'pa_type' => 4,
//            'sales_manger_id' => $manger_id,
//            'sales_manger_name' => $manger_name,
//            'create_at' => time(),
//        ];

        DB::beginTransaction();
        try {
            if ($dataSubIsSysItem) {
                $document_number = SnCode::getSnCode('XS_');
                $sysData = $data + ['document_number' => $document_number];
                $sysData["is_sys_purchase"] = '2';

                $sysData['examine_status'] = config('constants.examine_status.normal');
                //获取低于指导价审核总状态
                foreach ($dataSubIsSysItem as $sysItem) {
                    if ($sysItem['examine_status'] == config('constants.examine_status.in_review')) {
                        $sysData['examine_status'] = config('constants.examine_status.in_review');
                        break;
                    }
                }

                $pId = ModelSaleorder::create($sysData)->id;

                $data_im['sale_weight'] = $saleWeightIsSys;
                $data_im['sale_amount'] = $saleAmountIsSys;
                $data_im['sale_pieces'] = $salePiecesIsSys;

                if ($sysData['examine_status'] == config('constants.examine_status.normal')) {
                    $pIdImp = Saleimplementation::create($data_im)->id;


                }

                /**
                 *  扣库存 单位：g
                 *
                 *  点价订单，审核通过后，扣除库存;
                 *
                 *  低于指导价审核，如果订单触发，在创建订单时不锁库存，审核通过才锁库存。2025.05.22
                 *
                 *
                 */

                if ($sysData['examine_status'] == config('constants.examine_status.normal')) {
                    if (in_array($req_data['order_type'], ['1', '2', '3'])) {
                        $decr_stock = $this->incrDecrStockInSaleEdit($dataSubIsSysItem, 'decr', 'g');
                        if ($decr_stock['code'] != '000') {
                            return response()->json($decr_stock);
                        }
                    }
                }


                foreach ($dataSubIsSysItem as $key => $item) {
                    $dataSubIsSysItem[$key]['p_id'] = $pId;
                    $saleSubId = ModelSaleordersub::create($item + ['p_id' => $pId])->id;
                    if ($sysData['examine_status'] == config('constants.examine_status.normal')) {

                        if (empty($item['pieces'])) {
                            $pieces = 0;
                        } else {
                            $pieces = $item['pieces'];
                        }

                        $itemImp = array_merge($item,[
                            'p_id' => $pIdImp,
                            'sale_id' => $saleSubId,
                            'sale_weight' => $item['total_weight'],
                            'sale_amount' => $item['total'],
                            'sale_pieces' => $pieces,
                        ]);
                        Saleimplementationsub::create($itemImp);
                    }
                    $dataSubIsSysItem[$key]['sale_sub_id'] = $saleSubId ?? 0;
                }

                $saleOrder = ModelSaleorder::where('id', $pId)->first();
                //只有常规订单，不低于指导价的订单直接同步到采购
                if ($saleOrder->examine_status == 1 && $saleOrder->order_type == 1) {
                    $saleOrderSub = ModelSaleordersub::where('p_id', $pId)->get()->toArray();
                    $this->syncSaleToPurchaseOrder($saleOrder, $saleOrderSub);
//                    foreach ($dataSubIsSysItem as $value) {
//                        $dataSubPurchaseIsSys[$value['code']][] = $value;
//                    }

//                    foreach ($dataSubPurchaseIsSys as $item) {
//                        $order_sn_code = SnCode::getSnCode('PO_');
//                        $dataPurchase['order_sn_code'] = $order_sn_code;
//                        $order_id = PurchaseOrder::create($dataPurchase)->id;
//
//                        $dataPurchaseIm['order_id'] = $order_id;
//                        $dataPurchaseIm['order_sn_code'] = $order_sn_code;
//                        $im_order_id = PurchaseOrderProcess::create($dataPurchaseIm)->id;
//
//                        foreach ($item as $value) {
//                            $value['count'] = $value['pieces'];
//                            $value['order_id'] = $order_id;
//                            $value['sale_sub_id'] = $value['sale_sub_id'];
//                            $sub_order_id = PurchaseOrderSub::create($value)->id;
//
//                            $value['process_order_id'] = $im_order_id;
//                            $value['sub_order_id'] = $sub_order_id;
//                            PurchaseOrderProcessSub::create($value);
//                        }
//                    }
                }

                $update = [
                    'transactions_number' => $custom['transactions_number'] + 1,
                    'previous_order_date' => $custom['last_order_date'] ?? time(),
                    'last_order_date' => time(),
                    'total_transaction_tonnage' => $custom['total_transaction_tonnage'] + $saleWeightIsSys,
                ];
                if (empty($custom['first_order_date'])) {
                    $update['first_order_date'] = time();
                }
                Custom::where('id', $custom['id'])->update($update);
            }

            if ($dataSubIsNotSysItem) {
                $document_number = SnCode::getSnCode('XS_');
                $data = $data + ['document_number' => $document_number];

                $data['examine_status'] = config('constants.examine_status.normal');
                //获取低于指导价审核总状态
                foreach ($dataSubIsNotSysItem as $notSysItem) {
                    if ($notSysItem['examine_status'] == config('constants.examine_status.in_review')) {
                        $data['examine_status'] = config('constants.examine_status.in_review');
                        break;
                    }
                }

                $pId = ModelSaleorder::create($data)->id;

                $data_im['sale_weight'] = $saleWeightIsNotSys;
                $data_im['sale_amount'] = $saleAmountIsNotSys;
                $data_im['sale_pieces'] = $salePiecesIsNotSys;

                if ($data['examine_status'] == config('constants.examine_status.normal')) {
                    $pIdImp = Saleimplementation::create($data_im)->id;
                }
                /**
                 *  扣库存 单位：g
                 *
                 */
                if ($data['examine_status'] == config('constants.examine_status.normal')) {
                    if (in_array($req_data['order_type'], ['1', '2', '3'])) {
                        $decr_stock = $this->incrDecrStockInSaleEdit($dataSubIsNotSysItem, 'decr', 'g');
                        if ($decr_stock['code'] != '000') {
                            return response()->json($decr_stock);
                        }
                    }
                }
                foreach ($dataSubIsNotSysItem as $key => $item) {
                    $dataSubIsNotSysItem[$key]['p_id'] = $pId;
                    $saleSubId = ModelSaleordersub::create($item + ['p_id' => $pId])->id;
                    if ($data['examine_status'] == config('constants.examine_status.normal')) {
                        if (empty($item['pieces'])) {
                            $pieces = 0;
                        } else {
                            $pieces = $item['pieces'];
                        }
                        $itemImp = array_merge($item,[
                            'p_id' => $pIdImp,
                            'sale_id' => $saleSubId,
                            'sale_weight' => $item['total_weight'],
                            'sale_amount' => $item['total'],
                            'sale_pieces' => $pieces,
                        ]);
                        Saleimplementationsub::create($itemImp);
                    }
                }

//                $salefeedata = ModelSaleorderfee::where('order_number', $order_number)->get()->toArray();
//                if (!$salefeedata) {
//                    foreach ($otherfeedata as $key => $item) {
//                        $otherfeedata[$key]['order_number'] = $order_number;
//                        $other_pid = ModelSaleorderfee::create($otherfeedata[$key])->id;
//
//                        ModelSaleorderfee::where('id', $other_pid)->update([
//                            'other_pid' => $other_pid,
//                        ]);
//                    }
//                }

                $update = [
                    'transactions_number' => $custom['transactions_number'] + 1,
                    'previous_order_date' => $custom['last_order_date'] ?? time(),
                    'last_order_date' => time(),
                    'total_transaction_tonnage' => $custom['total_transaction_tonnage'] + $saleWeightIsSys,
                ];
                if (empty($custom['first_order_date'])) {
                    $update['first_order_date'] = time();
                }
                Custom::where('id', $custom['id'])->update($update);
            }
            //$CustomInfo = Custom::where('id', $custom['id'])->first();

            //--------订单合同扩展 2025.03.11--------------
//            $ContractPreviewExtendData = [
//                "cpid"=>$cpid,
//                "business_type" =>"sale_order",//销售订货
//                "serial_number" =>"1",
//                "source_id" =>$pId,
//                "letter_total_weight" =>$total_weight,
//                "letter_no" =>$data["order_number"],
//                "receive_person" =>$CustomInfo["company_name"],
//                "receive_person_phone" =>$CustomInfo["firm_phone_number"],
//                "letter_date" => $req_data['document_date'],
//                "create_at" => time()
//            ];
//            $contractFirst = \App\Models\Order\ContractPreviewExtend::dopostadd($ContractPreviewExtendData);
//            $ContractPreviewExtendDataTwo = $ContractPreviewExtendData;
//
//            $ContractPreviewExtendDataTwo["serial_number"] = "2";
//            $ContractPreviewExtendDataTwo["letter_no"] = "42DWR411"; //暂时写死
//            $contractTwo = \App\Models\Order\ContractPreviewExtend::dopostadd($ContractPreviewExtendDataTwo);
//            if($contractFirst["code"] == "001" || $contractTwo["code"] == "001"){
//                return $this->response()->json(["code"=>"001","msg"=>"合同信息添加失败"]);
//            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '销售订单添加失败' . $e->getMessage()]);
        }

        /**
         *  销售订单新增
         *
         *
         */
        //        $Chanjet_param = [
        //            "dto" => [
        //                "ExternalCode" => $document_number,
        //                "BusinessType" =>["Code"=>'15'], //15 普通销售 16 销售退货
        //                "Customer" => ["Code"=>Custom::where('id',$req_data['custom_id'])->value('company_code')],
        //                "SaleOrderDetails" => $SaleOrderDetails,
        //
        //            ]
        //        ];
        //        if($this->mangerinfo['org_id']) {
        //            ChanjetRequest::getInstance()->saleOrderCreate($Chanjet_param,$this->mangerinfo['org_id']);
        //        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $params = ['id', 'custom_id','custom_level','custom_name', 'document_date', 'wagon_number', 'driver_phone_number', 'suborder', 'remark', 'extra_type', 'order_type'];
        $req_data = $request->only($params);
        $validate = new Saleorder('edit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $sale_one = ModelSaleorder::where('id', $req_data['id'])->first();
        if (!$sale_one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $sale_one = $sale_one->toArray();

        /****
         * 以销定采的单子,销售订单修改，只能改价格，其他不可修改
         *  2025.05.23
         *
         */
        if ($sale_one['is_sys_purchase'] == '2') {
            //return response()->json(['code' => '001', 'msg' => ' 以销定采的销售订单不可修改']);
        }
        $SaleOrderStatusArr = $this->SaleOrderAuditStatus($req_data['id']);
        //获取订单状态是否审核中
        if ($SaleOrderStatusArr['code'] != '000') {
            return response()->json($SaleOrderStatusArr);
        }


        if (!empty($req_data['otherfee'])) {
            $otherfee = is_array($req_data['otherfee']) ? $req_data['otherfee'] : (is_array(json_decode($req_data['otherfee'], true)) ? json_decode($req_data['otherfee'], true) : []);
        } else {
            $otherfee = [];
        }

        //        $otherfeedata = [];
        $otherfeetotal = 0;
        $ValidateSub = new Saleorderfee('add');
        foreach ($otherfee as $fee) {
            $fee = is_array($fee) ? $fee : json_decode($fee, true);
            if (!$ValidateSub->check($fee)) {
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            $otherfeetotal = $otherfeetotal + $fee['price'];
        }

        $suborder = is_array($req_data['suborder']) ? $req_data['suborder'] : json_decode($req_data['suborder'], true);
        foreach ($suborder as $item) {
            if (isset($item['id'])) {
                $sale_sub_one = ModelSaleordersub::where('id', $item['id'])->first();
                if (!$sale_sub_one) {
                    return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                }
                $sale_sub_one = $sale_sub_one->toArray();
                // if ($sale_sub_one['produce_status'] == config('constants.produce_status.produced')) {
                //     return response()->json(['code' => '001', 'msg' => '已生成子订单不能编辑']);
                // }
                // if ($sale_sub_one['produce_status'] == config('constants.produce_status.produceing')) {
                //     return response()->json(['code' => '001', 'msg' => '生成中子订单不能编辑']);
                // }
                // if ($sale_sub_one['examine_status'] == config('constants.examine_status.in_review')) {
                //     return response()->json(['code' => '001', 'msg' => '审核中子订单不能编辑']);
                // }
                /***
                 * 修改时，非自采订单不能改为自采订单  王丹娜 2025.04.24
                 *
                 */
                if ($sale_sub_one['is_sys_purchase'] != $item['is_sys_purchase']) {
                    return response()->json(['code' => '001', 'msg' => '自采/非自采性质不能修改']);
                }

                /***
                 *  修改价格只能比之前低 不能比之前高
                 *
                 */
                if ($req_data['order_type'] == 3) {
                    $unit_price = mathfuncmoney('mul', $item['unit_price'], 100);
                    if ($unit_price <= 0) {
                        return response()->json(['code' => '001', 'msg' => '保价订单，单价必须大于0']);
                    }
                    if ($unit_price > $sale_sub_one['unit_price']) {
                        return response()->json(['code' => '001', 'msg' => '保价订单，单价不能比之前高']);
                    }
                }
            }
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;

        $price_data = $this->getsaleprice();
        if (isset($price_data['base']['基价'])) {
            $base_price = $price_data['base']['基价']['amount'];
        } else {
            return response()->json(['code' => '001', 'msg' => '基价不能为空']);
        }

        $custom = Custom::where('id', $req_data['custom_id'])->first();
        if (!$custom) {
            return response()->json(['code' => '001', 'msg' => '客户不存在']);
        }
        $custom = $custom->toArray();
        $preferential_price = $custom['preferential_price'] ?? 0;

        $sale_weight = $sale_amount = $sale_pieces = 0;
        $custom_level = $sale_one['custom_level'];

        $subvalidate = new Saleordersub('edit');

        $total_weight_sum = 0;
        foreach ($suborder as $item) {
            if (!$subvalidate->check($item)) {
                return response()->json(['code' => '001', 'msg' => $subvalidate->getError()]);
            }

            $guiding_price = $base_price;
            if ($req_data['extra_type'] == 1) {
                if (in_array($req_data['order_type'], ['1', '2', '3'])) {
                    $guiding_price = $this->getsteelprice($price_data, $base_price, $item);
                }
            }

            $unit_price = mathfuncmoney('mul', $item['unit_price'] ?? 0, 100);
            $item_total_weight_g = mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);
            $pieces = $item['pieces'] ?? 0;

            /***
             *  检查子订单数据，是否合法
             *
             */
            $res_check_suborder_item = $this->checkSubOrderItem('SaleOrder', $req_data, $item, $item_total_weight_g, $unit_price, $pieces);
            if ($res_check_suborder_item['code'] != '000') {
                return response()->json($res_check_suborder_item);
            }
            /***
             *  检查每个子订单,订单审核检查
             *
             */
            $order_review = $this->checkOrderReview($req_data, 'edit');
            if ($order_review['code'] != '000') {
                return response()->json($order_review);
            }
//            else{
//                if($order_status == config('constants.order_status.audit')){
//                    $order_status = $order_review['data']['order_status'];
//                }
//            }

            // if (in_array($req_data['order_type'], [1, 3])) {
            //     if ($unit_price <= $guiding_price) {
            //         Log::info('edit:unit_price:' . $unit_price . '  preferential_price:' . $preferential_price . '  guiding_price:' . $guiding_price);
            //         return response()->json(['code' => '001', 'msg' => '单价不能低于指导价']);
            //     }
            // }
            /***
             *  低于指导价审核，主订单examine_status=2  子订单，低于指导价的数据 examine_status=2
             *  子订单 低于指导价数据标红，为了提醒操盘。标红后，再审核不需要调整
             *  2025.04.23
             *  销售订单修改，只影响订单审核
             *
             */
            //$otherfeetotal_cent = mathfuncmoney('mul', $otherfeetotal??0, 100);
//            $res_guide_price = $this->checkLowGuidePrice($req_data,$custom,'edit',$unit_price,$guiding_price,$preferential_price,$item['is_sys_purchase'],$otherfeetotal_cent);
//            if($res_guide_price['code'] != '000'){
//                return response()->json($res_guide_price);
//            }else{
//                $sub_examine_status = $res_guide_price['data']['sub_examine_status'];
//            }
//            $sub_examine_status = config('constants.examine_status.normal');
//            if ($req_data['order_type'] == 1 || $req_data['order_type'] == 3) {
//                if ($custom['custom_level'] == 1) {
//                    if ($unit_price < $guiding_price) {
//                        return response()->json(['code' => '001', 'msg' => '单价不能低于指导价']);
//                    }
//                } else {
//                    if (($unit_price + $preferential_price) < $guiding_price) {
//                        $examine_status = $sub_examine_status = config('constants.examine_status.in_review');
//                    }
//                }
//
//                // if ($req_data['order_type'] == 3) {
//                //     $order_status = 2;
//                // }
//
//            } elseif ($req_data['order_type'] == 2) {
//                $examine_status = $sub_examine_status = config('constants.examine_status.in_review');
//                // $order_status = 2;
//            } elseif ($req_data['order_type'] == 4 || $req_data['order_type'] == 2) {
//                if ($item['is_sys_purchase'] == 2) {
//                    return response()->json(['code' => '001', 'msg' => '订单不能自采']);
//                }
//                // $order_status = 2;
//            }

            // if ($req_data['order_type'] == 1) {
            //     if (($unit_price + $preferential_price) < $guiding_price) {
            //         return response()->json(['code' => '001', 'msg' => '单价不能低于指导价']);
            //     }
            //     if ($custom_level == 1) {
            //         if ($unit_price < $guiding_price) {
            //             return response()->json(['code' => '001', 'msg' => '单价不能低于指导价']);
            //         }
            //     } else {
            //         if (($unit_price + $preferential_price) < $guiding_price) {
            //             $examine_status = $sub_examine_status = config('constants.examine_status.in_review');
            //         }
            //     }
            // }


            // $one = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'company_costs'])->first();
            // if ($one) {
            //     $companycosts = $one->value;
            // } else {
            //     $companycosts = 10;
            // }
            // if ($sale_one['order_type'] != 2) {
            //     if ($item['is_sys_purchase'] == 2) {
            //         return response()->json(['code' => '001', 'msg' => '自采单子不能编辑']);
            //     } else {
            //         $accrual = $unit_price - $guiding_price + $companycosts;
            //         $a = $accrual + $otherfeetotal;
            //         $b = mathfuncweight('div', $item['total_weight'] ?? 0, 10000, 4);
            //         // $b = $item['total_weight'] ?? 0;
            //         $performance = $accrual * $b;
            //         Log::info('计提:' . $accrual);
            //         Log::info('业绩:' . $performance . ';金额,' . $a . ';重量:' . $b);
            //     }
            // } else {
            //     $accrual = $unit_price - $base_price + $companycosts;
            //     $accrual = $unit_price - $guiding_price + $companycosts;
            //     $a = $accrual + $otherfeetotal;
            //     $b = mathfuncweight('div', $item['total_weight'] ?? 0, 10000, 4);
            //     // $b = $item['total_weight'] ?? 0;
            //     $performance = $accrual * $b;
            //     Log::info('计提:' . $accrual);
            //     Log::info('业绩:' . $performance . ';金额,' . $a . ';重量:' . $b);
            // }

            $pieces = $item['pieces'] ?? 0;
            $data_sub_item[] = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'material_id' => !empty($item['material_id']) ? $item['material_id'] : 0,
                'archive_no' => $item['archive_no'],
                'warehouse_name' => $item['warehouse_name'],
                'steel_factory_name' => $item['steel_factory_name'],
                'archive_type' => $item['archive_type'],
                'archive_name' => $item['archive_name'],
                'archive_spec' => $item['archive_spec'],
                'archive_material' => $item['archive_material'],
                'breed_name' => $item['breed_name'],
                'stock_id' => $item['stock_id'],
                'total_weight' => mathfuncweight('mul', $item['total_weight'], 10000),
                'pieces' => $pieces,
                'length' => $item['length'] ?? 0,
                'unit_price' => mathfuncweight('mul', $item['unit_price'], 100),
                'total' => mathfuncmoney('mul', $item['total'], 100),
                'accrual' => mathfuncmoney('mul', $item['accrual'] ?? 0, 100),
                'performance' => mathfuncmoney('mul', $item['performance'] ?? 0, 100),
                'examine_status' => $item['examine_status'],//销售订单审核
                'remark' => $item['remark'] ?? '',
                'create_at' => time(),
                'is_sys_purchase' => $item['is_sys_purchase'],
                'id' => $item['id']
            ];
            //低于指导价 子订单，不参与 销售订单执行表总计？
            //if ($item['examine_status'] == config('constants.examine_status.normal')) {
            $sale_weight = $sale_weight + mathfuncweight('mul', $item['total_weight'], 10000);
            $sale_amount = $sale_amount + mathfuncmoney('mul', $item['total'], 100);
            $sale_pieces = $sale_pieces + $pieces;
            //}
            $total_weight_sum += mathfuncweight('mul', $item['total_weight'], 10000, 4);
        }
        //增加验证, 操盘下 所有订单是否超重
        $is_over_weight = $this->checkSaleOrderOverWeight($cpid, $total_weight_sum);
        if ($is_over_weight["code"] != '000') {
            return response()->json($is_over_weight);
        }

        //低于指导价 主订单状态标记
        //$examine_status = config('constants.examine_status.normal');
//        if(!empty($data_sub_item)){
//            foreach ($data_sub_item as $data_sub_item_examine_status){
//                if($data_sub_item_examine_status['examine_status'] == config('constants.examine_status.in_review')){
//                    $examine_status = config('constants.examine_status.in_review');
//                    break;
//                }
//            }
//        }

        $data = [
            'document_date' => $req_data['document_date'],
            'wagon_number' => $req_data['wagon_number'] ?? '',
            'driver_phone_number' => $req_data['driver_phone_number'] ?? '',
            'examine_status' => config('constants.examine_status.normal'),
            'remark' => $req_data['remark'] ?? '',
            'order_status' => 2,
            'update_at' => time()
        ];

        DB::beginTransaction();
        try {
            $beforeData = ModelSaleorder::where('id', $req_data['id'])->with(['suborder' => function ($query) {
                $query->where('is_del', 1);
            }])->first();

            if($beforeData->customer_id != $req_data['custom_id'])
            {
                //如果修改了客户信息 需要判断下是否有已生成的发货单
                $is_have_sale_order = ModelSalesorder::where(['order_number'=>$beforeData->order_number,'is_del'=>1])->exists();
                if($is_have_sale_order)
                {
                    return response()->json(['code' => '001', 'msg' => '已经生成发货单，请勿修改客户信息']);
                }
                $data['custom_id'] = $req_data['custom_id'];
                $data['custom_level'] = $req_data['custom_level'];
                $data['custom_name'] = $req_data['custom_name'];
            }
            $oldSubList = ModelSaleordersub::where([
                ['p_id', $req_data['id']],
                ['is_del', 1]
            ])->get()->toArray();
            $newSubList = $suborder;
            /***
             *  返还旧订单库存,扣除新子订单  销售订单修改
             *  目前只能 删除/修改 2025.04.11
             *
             */
//            if(!empty($newSubList)){
//                foreach ($newSubList as $key => $new) {
//                    $newSubList[$key]['total_weight'] = mathfuncweight('mul', $new['total_weight'], 10000);
//                }
//            }

            $incr_stock = $this->incrDecrStockInSaleEdit($oldSubList, 'incr', 'g');
            if ($incr_stock['code'] != '000') {
                return response()->json($incr_stock);
            }

            $decr_stock = $this->incrDecrStockInSaleEdit($newSubList, 'decr');
            if ($decr_stock['code'] != '000') {
                return response()->json($decr_stock);
            }

            ModelSaleorder::where('id', $req_data['id'])->update($data);
            ModelSaleordersub::where('p_id', $req_data['id'])->update([
                'is_del' => config('constants.is_del.yes'),
                'update_at' => time()
            ]);
            //$sale_one

//            $sale_im_sub_produced = Saleimplementationsub::where([
//                ['p_id', $req_data['id']],
//                ['sales_id', '>', 0],
//            ])->get();
//
//            $sale_weight_pro = $sale_amount_pro = $sale_pieces_pro = 0;
//            if ($sale_im_sub_produced) {
//                $sale_im_sub_produced = $sale_im_sub_produced->toArray();
//                foreach ($sale_im_sub_produced as $item) {
//                    $sale_weight_pro = $sale_weight_pro + mathfuncweight('mul', $item['sale_weight'], 10000);
//                    $sale_amount_pro = $sale_amount_pro + $item['total'];
//                    $sale_pieces_pro = $sale_pieces_pro + $item['pieces'];
//                }
//            }

//            $data_im = [
//                'sale_weight' => $sale_weight + $sale_weight_pro,
//                'sale_amount' => $sale_amount + $sale_amount_pro,
//                'sale_pieces' => $sale_pieces + $sale_pieces_pro,
//                'update_at' => time(),
//            ];
            $data_im = [
                'sale_weight' => $sale_weight,
                'sale_amount' => $sale_amount,
                'sale_pieces' => $sale_pieces,
                'update_at' => time(),
            ];

            Saleimplementation::where('order_number', $sale_one['order_number'])
                ->update($data_im);
            $p_id_im = Saleimplementation::where('order_number', $sale_one['order_number'])->first();

            Saleimplementationsub::where([
                ['p_id', $p_id_im['id']],
//                ['sales_id', '=', 0],
            ])->update([
                'is_del' => config('constants.is_del.yes'),
                'update_at' => time()
            ]);
            if (!empty($p_id_im)) {
                $p_id_im = $p_id_im->id;

                foreach ($data_sub_item as $key => $item) {
                    $new_item = $item;
                    unset($new_item['id']);
                    $data_sub_item[$key]['p_id'] = $req_data['id'];
                    $new_sale_order_sub = $new_item + ['p_id' => $req_data['id']];
                    /**
                     *
                     *  更新销售订单执行表，同时删除旧销售子订单，新增新的销售子订单，暂时这样
                     *
                     *  修改销售订单后，子订单也修改了；如果是已销定采 需要更新 采购订单 sale_sub_id
                     *
                     *
                     */
                    $sale_sub_id = ModelSaleordersub::create($new_sale_order_sub)->id;

                    if ($item['is_sys_purchase'] == '2') {
                        PurchaseOrderSub::where(['is_del' => '1', 'sale_sub_id' => $item['id']])->update(
                            ['sale_sub_id' => $sale_sub_id]
                        );
                    }

                    if ($item['examine_status'] == config('constants.examine_status.normal')) {
                        $item_im = $item + [
                                'p_id' => $p_id_im,
                                'sale_id' => $sale_sub_id,
                                'sale_weight' => $item['total_weight'],
                                'sale_amount' => $item['total'],
                                'sale_pieces' => $item['pieces'],
                            ];
                        Saleimplementationsub::create($item_im);
                    }

                }
            }

            $afterData = ModelSaleorder::where('id', $req_data['id'])->with(['suborder' => function ($query) {
                $query->where('is_del', 1);
            }])->first();
            EditLog::create([
                'cpid' => $cpid,
                'order_type' => 11,
                'order_sn_code' => $beforeData->document_number,
                'before_data' => json_encode($beforeData->toArray()),
                'after_data' => json_encode($afterData->toArray()),
                'editor_mid' => $mangerinfo['id'],
                'editor_realname' => $mangerinfo['realname'],
                'create_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '销售订单编辑失败' . $e->getFile() . $e->getLine() . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelSaleorder::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['total_weight'] = mathfuncweight('div', $v['total_weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);
                $list['list'][$key]['suborder'][$k]['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                $list['list'][$key]['suborder'][$k]['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);
            }
            $list['list'][$key]['submit_del_audit_button'] = '2';//删除审核按钮默认不显示
            $list['list'][$key]['preview_contract_button'] = '2';//预览合同

            //合并审核状态，用来判定是否显示删除按钮
            if ($list['list'][$key]['produce_status'] == '1' && $list['list'][$key]['is_sys_purchase'] == '1') {
                if ((in_array($list['list'][$key]['del_status'], ['1', '4'])) && (in_array($list['list'][$key]['order_status'], ['1', '3']))) {
                    if ($list['list'][$key]['examine_status'] == '1' || $list['list'][$key]['examine_status'] == '3') {
                        $list['list'][$key]['submit_del_audit_button'] = '1';
                    }
                }
            }
            if (in_array($list['list'][$key]['order_status'], ['1', '3'])) {
                if (in_array($list['list'][$key]['examine_status'], ['1', '3'])) {
                    if ($list['list'][$key]['is_del'] == '1') {
                        $list['list'][$key]['preview_contract_button'] = '1';
                    }
                }
            }
            //显示销售订单状态
            if ($list['list'][$key]['order_status'] == '1' && $list['list'][$key]['examine_status'] == '1') {
                $list['list'][$key]['merge_status'] = '正常';
            }
            if ($list['list'][$key]['order_status'] == '3') {
                if (in_array($list['list'][$key]['examine_status'], ['1', '3'])) {
                    $list['list'][$key]['merge_status'] = '通过';
                }
            }
            if ($list['list'][$key]['examine_status'] == '3') {
                if (in_array($list['list'][$key]['order_status'], ['1', '3'])) {
                    $list['list'][$key]['merge_status'] = '通过';
                }
            }
            if ($list['list'][$key]['order_status'] == '4' || $list['list'][$key]['examine_status'] == '4') {
                $list['list'][$key]['merge_status'] = '驳回';
            }
            if ($list['list'][$key]['order_status'] == '2' || $list['list'][$key]['examine_status'] == '2') {
                $list['list'][$key]['merge_status'] = '审核中';
            }
            /***
             * del_status 删除状态，1未删除，2删除中，3已删除 4已驳回
             * is_del  是否删除，1否，2是
             *
             */

        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 低于指导价列表
     */
    public function getlowpricelist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelSaleorder::getLowPriceList($request, $memberinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }


    /**
     * 修改计提
     *
     */
    public function doupdateaccrual(Request $request)
    {
        $id = $request->id ?? 0;
        $accrual = $request->accrual ?? 0;

        // 校验参数
        if (!is_numeric($id) || $id <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效的订单ID']);
        }

        if (!is_numeric($accrual)) {
            return response()->json(['code' => '001', 'msg' => '计提金额必须是数字']);
        }
        $one = ModelSaleordersub::where('id', '=', $id)->first();
        if(!$one)
        {
            return response()->json(['code' => '001', 'msg' => '无效的订单ID']);
        }
        //examine_status 低于指导价审核状态，1正常、通过，2审核中,数据标红-低于指导价数据，4驳回   是否要判断审核状态不让修改

        ModelSaleordersub::where('id','=',$id)->update([
            'accrual'=>mathfuncweight('mul', $accrual, 100),
            'accrual_status'=>1,
        ]);

        Salesordersub::where('sale_id','=',$id)->update([
            'accrual_status'=>1,
        ]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $subIds = $request->subIds ?? '';
        /***
         * $subIds 参数，是为了返回子订单，根据 基价、加价规则，返回正确的单价。2025.05.15
         *
         */
        $suborder_ids = explode(',', $subIds);
        $one = ModelSaleorder::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $one = $one->toArray();
            $one['custom_balace'] = mathfuncmoney('div', $one['custom_balace'], 100, 2);
            /**
             *  2025.04.09 王丹娜, 根据加价规则取 销售单价/发货单价
             * 1.加价规则：取销售订单日期
             *   a.普通客户带出的单价默认为基价+加价，优惠客户的单价默认为基价+加价-优惠单价
             *   b.销售订单的单价可修改
             *   c.修改过后，发货的时候以修改过后的单价为准，不可在进行修改
             *
             * 2.加价规则：取销售订单发货日期
             *   a.普通客户带出的单价默认为基价,优惠客户的单价默认为基价优惠单价
             *   b.可进行修改
             *   c.修改过后，发货的时候以修改过后的单价+加价为准，不可在进行修改操作
             *
             *
             */
            $is_need_addprice = false;
            //取出单价，如果2 需要加价
            if ($one['extra_type'] == '2') {
                $is_need_addprice = true;
                $price_data = $this->getsaleprice();
            }
            if ($one['suborder']) foreach ($one['suborder'] as $key => $value) {
                if (!in_array($value['id'], $suborder_ids)) {
                    unset($one['suborder'][$key]);
                    continue;
                }
                $one['suborder'][$key]['weight'] = mathfuncweight('div', $value['weight'], 10000, 4);
                $one['suborder'][$key]['total_weight'] = mathfuncweight('div', $value['total_weight'], 10000, 4);

                $one['suborder'][$key]['total'] = mathfuncmoney('div', $value['total'], 100, 2);

                $one['suborder'][$key]['guiding_price'] = mathfuncmoney('div', $value['guiding_price'], 100, 2);

                $one['suborder'][$key]['accrual'] = mathfuncmoney('div', $value['accrual'], 100, 2);
                $one['suborder'][$key]['performance'] = mathfuncmoney('div', $value['performance'], 100, 2);
                $unit_price_into_yuan = mathfuncmoney('div', $value['unit_price'], 100, 2);
                if ($is_need_addprice) {
                    $addprice_unitPrice = $this->getsteelprice($price_data, $value['unit_price'], $value);
                    $unit_price_into_yuan = mathfuncmoney('div', $addprice_unitPrice, 100, 2);
                }
                $one['suborder'][$key]['unit_price'] = $unit_price_into_yuan;
            }
            $one['suborder'] = array_values($one['suborder']);

            $one['custom_balace_sy'] = mathfuncmoney('div', (Balance::where('custom_id', $one['custom_id'])->value('balance')), 100, 2);
            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception 预开发票的数据
     */
    public function getinvoiceone(Request $request)
    {
        $id = $request->id ?? 0;

        $one = ModelSaleorder::where('id', $id)
            ->where('is_del', config('constants.is_del.no'))
            ->first();

        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $oneinvoice = Saleorderinvoice::where([
            'order_number' => $one->order_number
        ])->first();

        if (!$oneinvoice) {
            //根据custom_id查询客户数据
            $custom_id = $one->custom_id;

            $one = ModelCustom::getone($custom_id);

            // 尝试将 bank_info 解析为数组，若解析失败则赋空数组
            $bank_info = is_array($one['bank_info']) ? $one['bank_info'] : json_decode($one['bank_info'], true) ?? [];
            $company_contacts = '';
            foreach ($bank_info as $value) {
                if ($value['is_default'] == 1) {
                    $company_contacts = $value['bank'];
                }
            }
            $returnone = [
                'custom_id' => $one['balance']['custom_id'],
                'company_contacts' => $company_contacts,
                'firm_name' => $one['firm_name'],
                'company_code' => $one['balance']['company_code'],
                'company_name' => $one['company_name'],
                'category' => $one['category'],
                'credit_code' => $one['credit_code'],
                'firm_address' => $one['firm_address'],
                'firm_phone_number' => $one['firm_phone_number'],
                'firm_bank' => $one['firm_bank'],
                'firm_bank_number' => $one['firm_bank_number'],
                'firm_email' => $one['firm_email'],
                'business_license' => $this->processField($one['business_license']),
                'account_opening_permit' => $this->processField($one['account_opening_permit']),
                'attorney' => $this->processField($one['attorney']),
            ];
            return response()->json(['code' => '000', 'msg' => '查询成功', 'data' => $returnone]);
        } else {
            $one = $oneinvoice->toArray();
            return response()->json(['code' => '000', 'msg' => '查询成功', 'data' => $one]);
        }
    }

    public function processField($value)
    {
        // 如果值为空，直接返回空数组
        if (empty($value)) {
            return '';
        }

        // 尝试将值解析为数组
        $decoded = is_array($value) ? $value : json_decode($value, true);

        // 检查是否解析成功并且是数组
        if (is_array($decoded)) {
            // 返回第一条数据，如果存在的话
            return !empty($decoded) ? array_values($decoded)[0] : '';
        }

        // 如果无法解析为数组，返回空数组
        return '';
    }


    /**
     * 发起删除
     * 已生成、待审核订单不能被删除
     */
    public function initdel(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelSaleorder::where('id', $id)->first()->toArray();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        // $starttoday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        // if ($one['create_at'] < $starttoday) {
        //     return response()->json(['code' => '001', 'msg' => '只能删除当天创建的订单']);
        // }

        if (!in_array($one['del_status'], ['1', '4'])) {
            return response()->json(['code' => '001', 'msg' => '删除中/已删除订单，不能被删除']);
        }

        if ($one['is_sys_purchase'] == 2) {
            return response()->json(['code' => '001', 'msg' => '自采订单不能被删除']);
        }

        $sale_list = ModelSaleordersub::where('p_id', $id)->get()->toArray();
        foreach ($sale_list as $item) {
            if ($item['produce_status'] == config('constants.produce_status.produced')) {
                return response()->json(['code' => '001', 'msg' => '已生成子订单不能被删除']);
            }
            if ($item['produce_status'] == config('constants.produce_status.produceing')) {
                return response()->json(['code' => '001', 'msg' => '生成中子订单不能被删除']);
            }
            if ($item['examine_status'] == config('constants.examine_status.in_review')) {
                return response()->json(['code' => '001', 'msg' => '审核中子订单不能被删除']);
            }
        }

        $data = [
            'del_status' => $request->status ?? config('constants.del_status.deleting'),
            'update_at' => time()
        ];
        ModelSaleorder::where('id', $id)->update($data);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 处理删除
     * 通过 del_status 3  驳回 4
     *
     */
    public function handledel(Request $request)
    {
        $cpid = $this->mangerinfo["cpid"];
        $manger_id = $this->mangerinfo['id'];
        $params = ['id', 'del_status'];

        $req_data = $request->only($params);
        $validate = new Saleorder('handledel');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $id = $req_data['id'];
        $one = ModelSaleorder::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        $del_status = $req_data['del_status'];
        if ($del_status == config('constants.del_status.deleted')) {
            $is_del = config('constants.is_del.yes');

        } else {
            $is_del = config('constants.is_del.no');
        }

        $data = [
            'del_status' => $del_status,
            'is_del' => $is_del,
            'update_at' => time(),
            'del_status_at' => time(),
            'del_status_mid' => $manger_id
        ];

        $one = $one->toArray();
        $data_im = [
            'is_del' => $is_del,
            'update_at' => time()
        ];

        DB::beginTransaction();
        try {
            ModelSaleorder::where('id', $id)->update($data);
            Saleimplementation::where('order_number', $one['order_number'])->update($data_im);

            if ($del_status == config('constants.del_status.deleted')) {
                $sub_list = ModelSaleordersub::where('p_id', $id)->get()->toArray();
                $amout = 0;
                if ($sub_list) foreach ($sub_list as $item) {
                    Stock::where(['id' => $item['stock_id']])->update([
                        'can_use_pieces' => DB::raw('can_use_pieces + ' . $item['pieces'] ?? 0),
                        'can_use_weight' => DB::raw('can_use_weight + ' . $item['total_weight'] ?? 0),
                        'locked_pieces' => DB::raw('locked_pieces - ' . $item['pieces'] ?? 0),
                        'locked_weight' => DB::raw('locked_weight - ' . $item['total_weight'] ?? 0)
                    ]);

                    ModelSaleordersub::where('id', $item['id'])->update([
                        'produce_status' => 1,
                        'is_del' => config('constants.is_del.yes'),
                        'update_at' => time()
                    ]);

                    $amout += $item['total'];
                }
                Log::info('订单删除，订单号：' . $one['order_number'] . '，金额：' . $amout);
                if ($amout > 0) {
                    \App\Services\Balance\Balance::SaleRefund($one['custom_id'], $cpid, $amout, $manger_id, '1');
//                    Balance::where(['custom_id' => $one['custom_id']])->update([
//                        'balance' => DB::raw('balance + ' . $amout)
//                    ]);
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 产品经理，处理低于指导价
     * 低于指导价审核
     *
     *
     *
     */
    public function handlebelow(Request $request)
    {
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;

        $params = ['id', 'examine_status'];
        $req_data = $request->only($params);
        $validate = new Saleorder('handlebelow');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $id = $req_data['id'];
        $one = ModelSaleorder::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $one = $one->toArray();
            DB::beginTransaction();
            try {
                $data = [
                    'examine_status' => $req_data['examine_status'],
                    'update_at' => time()
                ];
                ModelSaleorder::where('id', $id)->update($data + [
                        'examine_status_mid' => $this->mangerinfo['id'],
                        'examine_status_manger_name' => $this->mangerinfo['realname'],
                        'examine_status_at' => time(),
                        'statistics_at' => time(),
                    ]);


                ModelSaleordersub::where('p_id', $id)->update($data);


//                $groupStockPieces=[];
//                $groupStockWeight =[];

                if ($req_data['examine_status'] == config('constants.examine_status.pass')) {
                    $subList = ModelSaleordersub::where('p_id', $id)->get()->toArray();
                    $saleWeight = 0;
                    $saleAmount = 0;
                    $salePieces = 0;

                    foreach ($subList as $item) {
                        $saleWeight = $saleWeight + $item['total_weight'] ?? 0;
                        $saleAmount = $saleAmount + $item['total'] ?? 0;
                        $salePieces = $salePieces + $item['pieces'] ?? 0;

//                        $groupStockPieces[$item['stock_id']][] =$item['pieces']??0;
//                        $groupStockWeight[$item['stock_id']][] =$item['total_weight']??0;
                    }

                    /***
                     * 低于指导价 审核通过，锁库存
                     * 销售订单执行表，审核通过 创建
                     *
                     */
                    $decrStock = $this->incrDecrStockInSaleEdit($subList, 'decr', 'g');
                    if ($decrStock['code'] != '000') {
                        throw new \Exception($decrStock['msg']);
                    }
//                    foreach ($groupStockPieces as $stock_id=>$pieces){
//                        $total_pieces = array_sum($pieces);
//                        Stock::query()->where(['id' => $stock_id])->update([
//                            'can_use_pieces' => DB::raw('can_use_pieces + ' .$total_pieces),
//                            'locked_pieces' => DB::raw('locked_pieces - ' . $total_pieces),
//                        ]);
//                    }
//                    foreach ($groupStockWeight as $stock_id=>$weight){
//                        $total_weight = array_sum($weight);
//                        Stock::query()->where(['id' => $stock_id])->update([
//                            'can_use_weight' => DB::raw('can_use_weight + ' .$total_weight),
//                            'locked_weight' => DB::raw('locked_weight - ' . $total_weight),
//                        ]);
//                    }


                    $data_im = [
                        'cpid' => $one['cpid'],
                        'manger_id' => $manger_id,
                        'manger_name' => $one['manger_name'],
                        'order_number' => $one['order_number'],
                        'document_date' => $one['document_date'],
                        'custom_id' => $one['custom_id'],
                        'custom_name' => $one['custom_name'],
                        // 'settlement_company' => $one->settlement_company,
                        'sale_weight' => $saleWeight,
                        'sale_amount' => $saleAmount,
                        'sale_pieces' => $salePieces,
                        'create_at' => time(),
                    ];

                    $pIdImp = Saleimplementation::create($data_im)->id;
                    foreach ($subList as $item) {

                        $itemImp = array_merge($item , [
                                'p_id' => $pIdImp,
                                'sale_id' => $item['id'],
                                'sale_weight' => $item['total_weight'] ?? 0,
                                'sale_amount' => $item['total'] ?? 0,
                                'sale_pieces' => $item['pieces'] ?? 0,
                            ]);

                        unset($itemImp['id']);
                        $itemImp['weight'] = (int)$itemImp['total_weight'] ?? 0;
                        Saleimplementationsub::create($itemImp);
                    }
                    /***
                     *  创建订单时，自采/非自采，分组创建销售订单，订单性质 不会出现混合情况
                     *  order_status=3 订单审核通过 examine_status=3 低于指导价通过
                     *  2025.04.29
                     *
                     */
                    $sale_order_info = ModelSaleorder::where('id', $req_data['id'])->first();
                    if ($sale_order_info['examine_status'] == '3' && in_array($sale_order_info['order_status'], ['1', '3'])) {
                        if ($sale_order_info['is_sys_purchase'] == '2') {
                            $this->syncSaleToPurchaseOrder($sale_order_info, $subList);
                        }
                    }
                }
                /***
                 * 低于指导价审核-驳回，返还库存
                 *
                 *
                 */
                if ($req_data['examine_status'] == config('constants.examine_status.reject')) {
                    $subList = ModelSaleordersub::where('p_id', $id)->get()->toArray();
                    $incrStock = $this->incrDecrStockInSaleEdit($subList, 'incr', 'g');
                    if ($incrStock['code'] != '000') {
                        throw new \Exception($incrStock['msg']);
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getFile() . $e->getLine() . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '操作成功']);
        }
    }

    /**
     * 获取销售基价、加价
     */
    public function getsaleprice()
    {
        $mangerinfo = $this->mangerinfo;

        $data= (new  \App\Services\SaleOrder\SaleOrder())->getsaleprice($mangerinfo);
        return $data;
    }

    /**
     * 获取钢材加价
     */
    public function getsteelprice($price_data, $base_price, $item)
    {
         return (new  \App\Services\SaleOrder\SaleOrder())->getsteelprice($price_data, $base_price, $item);
    }

    public function getprice(Request $request)
    {
        $suborder = is_array($request['suborder']) ? $request['suborder'] : json_decode($request['suborder'], true);

        $custom = Custom::where('id', $request['custom_id'])->first()->toArray();

        /***
         * 获取 extra_type 加价规则
         * 1.销售订单日期  所有阶段，单价=基价+加价-优惠价
         * 2.销售订单发货日期 销售订单创建时,单价=基价-优惠价。发货单时，单价=销售订单价+加价
         *
         */
        //价格计算是否去除 加价
        $removeAddPrice = false;
        if (isset($request['extra_type']) && $request['extra_type'] == '2') {
            if (isset($request['sale_node']) && $request['sale_node'] == 'sale_order') {
                $removeAddPrice = true;
            }
        }

        if ($custom['custom_level'] == 2) {
            $preferential_price = $custom['preferential_price'];
        } else {
            $preferential_price = 0;
        }

        $price_data = $this->getsaleprice();
        if (isset($price_data['base']['基价'])) {
            $base_price = $price_data['base']['基价']['amount'];
        } else {
            return response()->json(['code' => '001', 'msg' => '基价不能为空']);
        }

        $res = [];
        foreach ($suborder as $key => $item) {
            // $res[$key]['id'] = $item['id'];
            $res[$key]['warehouse_name'] = $item['warehouse_name'];
            $res[$key]['archive_type'] = $item['archive_type'];
            $res[$key]['archive_no'] = $item['archive_no'];
            $res[$key]['archive_name'] = $item['archive_name'];
            $res[$key]['archive_spec'] = $item['archive_spec'];
            $res[$key]['archive_material'] = $item['archive_material'];
            $res[$key]['stock_id'] = $item['stock_id'];
            $res[$key]['can_use_weight'] = $item['can_use_weight'];
            $res[$key]['current_pieces'] = $item['current_pieces'];
            // $res[$key]['can_use_pieces'] = $item['can_use_pieces'];
            // $res[$key]['locked_pieces'] = $item['locked_pieces'];
            // $res[$key]['locked_weight'] = mathfuncmoney('div', $item['locked_weight'], 10000);
            // $res[$key]['current_pieces'] = $item['current_pieces'];
            // $res[$key]['storage_waiting_pieces'] = $item['storage_waiting_pieces'];
            // $res[$key]['storage_waiting_weight'] = mathfuncweight('div', $item['storage_waiting_weight'], 10000, 4);
            // $res[$key]['supply_add_price'] = mathfuncmoney('div', $item['supply_add_price'], 100, 2);
            // $res[$key]['avg_wight'] = $item['avg_wight'];
            $res[$key]['steel_factory_name'] = $item['steel_factory_name'];
            $res[$key]['breed_name'] = $item['breed_name'];
            // $res[$key]['substock'] = $item['substock'];
            // $res[$key]['supply_base_price'] = mathfuncmoney('div', $item['supply_base_price'], 100, 2);
            // $res[$key]['supply_price'] = mathfuncmoney('div', $item['supply_price'], 100, 2);
            // $res[$key]['custom_base_price'] = mathfuncmoney('div', $item['custom_base_price'], 100, 2);
            // $res[$key]['custom_add_price'] = mathfuncmoney('div', $item['custom_add_price'], 100, 2);
            // $res[$key]['custom_price'] = mathfuncmoney('div', $item['custom_price'], 100, 2);
            // $res[$key]['unit_price'] = mathfuncmoney('div', $item['unit_price'], 100, 2);
            //此处 guiding_price 有歧义, 这个值是直接返回,销售钢材显示价格(非指导价)
            if ($removeAddPrice) {
                $guiding_price = $base_price;
            } else {
                $guiding_price = $this->getsteelprice($price_data, $base_price, $item);
            }
            //基价-客户优惠价 可能为负数, 要等王丹娜决定 怎么处理
            $res[$key]['guiding_price'] = mathfuncmoney('div', $guiding_price - $preferential_price, 100, 2);
            $res[$key]['preferential_price'] = mathfuncmoney('div', $preferential_price, 100, 2);
            $res[$key]['index'] = !empty($item['index']) ? $item['index'] : '';
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $res]);
    }

    public function preview(Request $request)
    {
        $id = $request->id ?? 0;

        $memberinfo = $this->mangerinfo;
        $cpid = $memberinfo['cpid'] ?? 0;

        $one = ModelSaleorder::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $one = $one->toArray();
        if ($one['suborder']) foreach ($one['suborder'] as $key => $value) {
            $one['suborder'][$key]['weight'] = $value['weight'] != 0 ? $value['weight'] / 10000 : 0;
            $one['suborder'][$key]['total_weight'] = $value['total_weight'] != 0 ? $value['total_weight'] / 10000 : 0;
            $one['suborder'][$key]['unit_price'] = $value['unit_price'] != 0 ? $value['unit_price'] / 100 : 0;
            $one['suborder'][$key]['total'] = $value['total'] != 0 ? $value['total'] / 100 : 0;
            $one['suborder'][$key]['guiding_price'] = $value['guiding_price'] != 0 ? $value['guiding_price'] / 100 : 0;
            $one['suborder'][$key]['accrual'] = $value['accrual'] != "" ? $value['accrual'] / 100 : 0;
            $one['suborder'][$key]['performance'] = $value['performance'] != "" ? $value['performance'] / 100 : 0;
        }
        $custom_id = $one['custom_id'];
        $custom = Custom::where(['id' => $custom_id])->first()->toArray();
        $one['custom_info'] = $custom;
        //合同确认函字段
        $one['contract_extend'] = \App\Models\Order\ContractPreviewExtend::where(["source_id" => $id, "business_type" => "sale_order"])->get();
        $one['settle_company_info'] = SettleCompany::where(['settle_company_name' => $one['settlement_company'], 'cpid' => $cpid])->first();
        //合同印章获取
        $one['seal_filepath'] = null;
        if (isset($one['settle_company_info']['id'])) {
            $one['seal_filepath'] = TemplateContractsStamp::where(['company_id' => $one['settle_company_info']['id'], 'cpid' => $cpid, 'status' => '1'])->value('seal_filepath');
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    public function count(Request $request)
    {

        $cpid = $this->mangerinfo['cpid'] ?? 0;
        $list = ModelSaleorder::count($request,$cpid);
        if ($list) {
            foreach ($list['list'] as $k => $v) {
                // $list['list'][$k]['total'] = $v['total'] == 0 ? 0 : $v['total'] / 10000;
                $v->total = $v->total == 0 ? 0 : $v->total / 10000;
            }
        } else {
            $list = [];
        }

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    public function getunpasscount(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $manger_id = $memberinfo['id'] ?? 0;
        $cpid = $memberinfo['cpid'] ?? 0;

//        $tuikuanCount = CustomRefund::where([
//            'cpid' => $cpid,
//            'audit_status' => 1
//        ])->count();

        /***
         *  退货审核
         *  统审 可看到自己账套所有数据
         *
         **/
        $returnCount = Returnordersub::where([
            'cpid' => $cpid,
            'return_status' => 2
        ])->count();

        /**
         *  退款审核
         *  1.统审审核 audit_status 1->2
         *  2.操盘审核 audit_status 2->3
         *  审核先后有序  王丹娜说的 2025.03.31
         */
        $tuikuanCount = 0;
        if ($memberinfo['utype'] == '4') { //统审
            $tuikuanCount = CustomRefund::where([
                'cpid' => $cpid,
                'approve_id1' => $manger_id,
                'audit_status' => '1'
            ])->count();
        }
        if ($memberinfo['utype'] == '2') { //操盘
            $tuikuanCount = CustomRefund::where([
                'cpid' => $cpid,
                'approve_id2' => $manger_id,
                'audit_status' => '2'
            ])->count();
        }


        $lowCount = ModelSaleordersub::where([
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'examine_status' => config('constants.examine_status.in_review'),
            'is_del' => config('constants.is_del.no')
        ])->count();

        $delCount = ModelSaleorder::where([
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'del_status' => 2,
            'is_del' => 1
        ])->count();

        $saleCount = ModelSaleorder::where([
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'is_del' => 1
        ])->whereIn('order_status', [2])->count();

        /**
         *  退款审核
         *  1.统审审核 audit_status 1->2
         *  2.操盘审核 audit_status 2->3
         *  审核先后有序  王丹娜说的 2025.03.31
         */
        $fukuanCount = 0;
        if ($memberinfo['utype'] == '4') { //统审
            $fukuanCount = PurchasePayOrderApprove::where([
                'cpid' => $cpid,
                'approve_id1' => $manger_id,
                'audit_status' => 1,
                'is_del' => 1
            ])->count();
        }
        if ($memberinfo['utype'] == '2') { //操盘
            $fukuanCount = PurchasePayOrderApprove::where([
                'cpid' => $cpid,
                'approve_id2' => $manger_id,
                'audit_status' => 2,
                'is_del' => 1
            ])->count();
        }




        /**
         * 操盘2,票务3,统审4,仓库5,采购6,销售7,出纳8
         * 审核顺序 1.统审 2.操盘
         * 审核状态1 未审核 2 一个审核通过  3 审核完成 4 审核驳回
         */
        $xiaoshouCount = 0;
        if ($memberinfo['utype'] == '2') { //操盘
            $xiaoshouCount = SaleorderOtherfeePay::where([
                'cpid' => $cpid,
                'is_del' => 1
                ])->whereHas('approve', function ($query) {
                    $query->where('status', 2);
                })
//                ->whereIn("status", ["2"])
                ->count();
        }
        if ($memberinfo['utype'] == '4') { //统审
            $xiaoshouCount = SaleorderOtherfeePay::where([
                    'cpid' => $cpid,
                    'is_del' => 1
                ])->whereHas('approve', function ($query) {
                    $query->where('status', 1);
                })
//                ->whereIn("status", ["1"])
                ->count();
        }
        //订单差额较大审核(统审)
        $diffCount = Saleimplementation::where([
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'status' => 2,
            'is_del' => 1
        ])->count();

        $baochedanCount = ModelSalesorder::where([
            'cpid' => $cpid,
            'baochedan_status' => 2,
            'is_del' => 1
        ])->count();

        $warehousingCount = PurchaseWarehousingOrder::where([
            'cpid' => $cpid,
            'is_del' => 1
        ])->whereIn('audit_status', [2])->count();

        //新增采购费用审核数量purchase_pay_order_approve
        $purchaseCount = 0;
        if ($memberinfo['utype'] == '4') { //统审
            $purchaseCount = ExpenseVoucherInfoPay::where([
                'cpid' => $cpid,
                'is_del' => 1
            ])->whereHas('approve', function ($q) use ($manger_id) {
                $q->where('approve_id1', $manger_id)->where('audit_status', 1);
            })->count();
        }
        if ($memberinfo['utype'] == '2') { //操盘
            $purchaseCount = ExpenseVoucherInfoPay::where([
                'cpid' => $cpid,
                'is_del' => 1
            ])->whereHas('approve', function ($q) use ($manger_id) {
                    $q->where('approve_id1', $manger_id)->where('audit_status', 2);
                })->count();
        }


        //新增销售出库单审核数量outbound_order_sub
        $saleWarehouseCount = Outboundordersub::where([
            'cpid' => $cpid,
            'examine_status' => 2,
        ])->count();


        $totalCount = $returnCount + $lowCount + $delCount + $lowCount + $saleCount + $fukuanCount + $tuikuanCount + $xiaoshouCount + $baochedanCount + $warehousingCount + $purchaseCount + $saleWarehouseCount;

        return response()->json([
            'code' => '000',
            'msg' => '操作成功',
            'data' => [
                'total_count' => $totalCount,
                'return_count' => $returnCount, //退货单审核
                'low_count' => $lowCount, //低于指导价
                'del_count' => $delCount, //删除销售订单审核
                'diff_count' => $diffCount, //销售订单结束差额较大审核
                'sale_count' => $saleCount,//销售订单审核
                'fukuan_count' => $fukuanCount,//付款审核
                'tuikuan_count' => $tuikuanCount,//退款审核
                'xiaoshou_count' => $xiaoshouCount,//销售费用审核
                'baochedan_count' => $baochedanCount,//报车单审核
                'warehousingCount' => $warehousingCount, //采购入库单审核
                'purchaseCount' => $purchaseCount, //采购费用审核
                'saleWarehouseCount' => $saleWarehouseCount //销售出库单审核
            ]
        ]);
    }

    /***
     *  销售订单审核功能
     *
     *  审核通过  order_status  3
     *  审核驳回  order_status  4
     *
     *  销售订单创建，无需审核时，已销定采的销售订单直接同步到采购订单；
     *  销售订单创建时，已销定采和非已销定采会 拆分为两个订单，自采和非自采
     *
     *  锁量不锁规格订单（重量已有），也需要同步到采购订单
     *
     *  销售订单创建，需要审核时，（低于指导价审核/订单审核）必须全部通过后，才同步采购订单
     *
     *  2025.04.25 王丹娜
     *
     *
     *  已销定采，同步时 销售订单子数据同步生成采购订单，父子数据都需要同步（公共属性 销售订单号）
     *  父订单：合同号，结算公司（编辑时补充） 单据编号，日期（系统生成） 销售订单号，销售姓名，票据类型（同步）
     *  子订单自己输入：基价+加价。其余属性现有系统已正常
     *
     *  根据暗码合并同步的采购子订单，到采购主订单
     *
     *  点价订单（后结算）审核通过后，扣库存; 价格不确定，不存在低于指导价
     *
     */
    public function handleorder(Request $request)
    {
        $params = ['id', 'order_status'];
        $req_data = $request->only($params);
        $validate = new Saleorder('order_status');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }
        if (!in_array($req_data['order_status'], ['3', '4'])) {
            return response()->json(['code' => '001', 'msg' => '审核状态异常！']);
        }
        $id = $req_data['id'];
        $data = [
            'order_status' => $req_data['order_status'],
            'update_at' => time(),
            'order_status_mid' => $this->mangerinfo['id'],
            'order_status_manger_name' => $this->mangerinfo['realname'],
            'order_status_at' => time()
        ];
        DB::beginTransaction();
        try {
            $num = ModelSaleorder::where('id', $id)->update($data);
            if ($num === 0) {
                throw new \Exception("审核失败，未找到记录或数据未更改");
            }
            $info = ModelSaleorder::where('id', $id)->first();
            /***
             * 审核通过，点价订单 扣库存
             *
             */
            if ($info['order_status'] == '3' && $info['order_type'] == '4') {
                $infoSub = ModelSaleordersub::where('p_id', $id)->get()->toArray();
                $incrStock = $this->incrDecrStockInSaleEdit($infoSub, 'decr', 'g');
                if ($incrStock['code'] != '000') {
                    throw new \Exception($incrStock['msg']);
                }
            }
            //order_status=3 订单审核通过 examine_status=3 低于指导价通过
            if ($info['order_status'] == '3' && in_array($info['examine_status'], ['1', '3'])) {
                $infoSub = ModelSaleordersub::where('p_id', $id)->get()->toArray();
                $this->syncSaleToPurchaseOrder($info, $infoSub);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败，' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核成功']);
    }


    public function getotherfeepayinfo(Request $request)
    {
        $otherfee_id = intval($request->otherfee_id);
        $cpid = $this->mangerinfo['cpid'] ?? 0;

        $otherfeeinfo = ModelSaleorderfee::where(['cpid' => $cpid, 'id' => $otherfee_id])->first();

        if (!$otherfeeinfo) {
            return response()->json(['code' => '001', 'msg' => '费用信息不存在']);
        }

        $custominfo = Custom::where(['id' => $otherfeeinfo->company_id, 'category' => 3])->first();

        $custominfo['tplus_company_name'] = CustomController::getFullnameInCustom($custominfo->toArray());

        $bankinfo = isset($custominfo->bank_info) ? json_decode($custominfo->bank_info, true) : [];
        $payment_info = isset($custominfo->payment_info) ? json_decode($custominfo->payment_info, true) : [];

        $return_data = [
            'bankinfo' => $bankinfo,
            'payment_info' => $payment_info,
            'custominfo' => $custominfo,
            'otherfeeinfo' => $otherfeeinfo,
        ];

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $return_data]);
    }
    /****
     *  销售其他费用，每次付款新增 付款数据，不存在修改，数据撤审后 当前付款数据 废弃
     *
     *
     */
    public function dopostpayotherfee(Request $request)
    {
        $otherfee_id = intval($request->otherfee_id);
        $cpid = $this->mangerinfo['cpid'] ?? 0;
        $otherfeeinfo = ModelSaleorderfee::where(['cpid' => $cpid, 'id' => $otherfee_id])->orderBy('id', 'desc')->first();

        if (!$otherfeeinfo) {
            return response()->json(['code' => '001', 'msg' => '费用信息不存在']);
        }
        /***
         *  status 1 待审核 2 审核中 3审核通过 4已驳回
         *
         *  审核中 禁止编辑，驳回后，重新生成
         *
         */
        //其他费用,数据驳回后重新发起流程，检查是否有新发起审批
        if ($otherfeeinfo->is_pay != 1 && in_array($otherfeeinfo->status, ['2','3'])) {
            return response()->json(['code' => '001', 'msg' => '订单审核中或审核成功，不允许再次编辑！']);
        }
        //发起付款审核 新增/编辑
        if((int)$otherfeeinfo->status == 1 || (int)$otherfeeinfo->status == 4 ){
            DB::beginTransaction();
            try {
                //再次申请的时候解除老的审批关联
                SaleorderOtherfeePay::where(['other_pid' => $otherfee_id])->update(['old_other_pid'=>$otherfee_id,'other_pid'=>0]);
                $data = ['is_pay' => 2, 'pay_at' => time(), 'pay_mid' => $this->mangerinfo['id']];
                $data['total_pieces'] = intval($request->total_pieces);
                $data['custom_name'] = strval($request->custom_name);
                $data['settlement_company'] = strval($request->settlement_company);
                $data['account_name'] = strval($request->account_name);
                $data['bank_card_no'] = strval($request->bank_card_no);
                $data['bank'] = strval($request->bank);
                $data['bank_number'] = strval($request->bank_number);
                $data['fee_num'] = intval($request->settlement_price);      //2025-09-16费用单价修改为结算金额
                $data['jj_mark'] = strval($request->jj_mark);
                $data['ts_mid'] = intval($request->ts_mid);
                $data['cp_mid'] = intval($request->cp_mid);
                $data['fee_type_name'] = $request->fee_type_name;
                $data['fee_name'] = $request->fee_name;
                $data['fee_number'] = $request->fee_number;
                $data['order_number'] = $request->order_number;
                $data['payment_info'] = is_array($request->payment_info) ? json_encode($request->payment_info) : $request->payment_info;
                $data['pay_bank'] = intval($request->pay_bank);
                $data['status'] = 1;
                SaleorderOtherfeePay::create($data + [
                        'cpid' => $cpid,
                        'other_pid' => $otherfee_id
                    ]);
                ModelSaleorderfee::where(['cpid' => $cpid, 'id' => $otherfeeinfo->id])->update([
                    'status'=>2,
                ]);
                DB::commit();

            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '付款失败，' . $e->getMessage()]);
            }
        }
        return response()->json(['code' => '000', 'msg' => '付款成功']);
    }
    /**
     * 销售订单同步到采购订单
     *
     * @param array $salerorder 销售主订单
     * @param array $ordersub 子订单数据
     * @return boolean
     *
     */
    public function syncSaleToPurchaseOrder($salerorder, $ordersub)
    {
        //查询已销定采订单是否创建
        $existIs_from_sale = PurchaseOrder::where(['is_del' => 1, 'cpid' => $salerorder['cpid'], 'is_from_sale' => '2',
            'sale_order_number' => $salerorder['order_number']])->first();
        if ($existIs_from_sale) return true;
        Log::info("销售订单同步到采购，订单号：" . $salerorder['order_number']);

        $mangerinfo = $this->mangerinfo;
        //$cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? '';
        //$purchaseOrder = [];
        $purchaseOrderSub = [];
        $purchaseOrderSubGroupByCode = [];
        foreach ($ordersub as $item) {
            if ($item['is_sys_purchase'] == 2) {
                $purchaseOrderSub[] = [
                    'cpid' => $item['cpid'],
                    'stock_id' => $item['stock_id'] ?? 0,
                    'count' => $item['pieces'] ?? 0,
                    'create_count' => 0,
                    'weight' => mathfunc('div', $item['total_weight'], $item['pieces'], 4),
                    'total_weight' => $item['total_weight'] ?? 0,
                    'create_weight' => 0,
                    'price' => $unit_price ?? 0,
//                    'total_money' => $item['total'] ?? 0,
                    'total_money' => 0,
                    'warehouse_name' => $item['warehouse_name'] ?? '',
                    'archive_no' => $item['archive_no'] ?? '',
                    'archive_name' => $item['archive_name'] ?? '',
                    'archive_spec' => $item['archive_spec'] ?? '',
                    'archive_material' => $item['archive_material'] ?? '',
                    'steel_factory_name' => $item['steel_factory_name'] ?? '',
                    'breed_name' => $item['breed_name'] ?? '',
                    'archive_type' => $item['archive_type'] ?? 0,
                    'remark' => $item['remark'] ?? '',
                    'sale_sub_id' => $item['id'],
                    'create_at' => time(),
                    'code' => $item['code'] ?? '',
                ];
                Log::info("销售子订单id:" . $item['id'] . ',单重：' . mathfunc('div', $item['total_weight'], $item['pieces'], 4) . ',总重：' . $item['total_weight'] . ',件数：' . $item['pieces']);
            }
        }
        if (!empty($purchaseOrderSub)) {
            foreach ($purchaseOrderSub as $value) {
                $purchaseOrderSubGroupByCode[$value['code']][] = $value;
            }
        }

        foreach ($purchaseOrderSubGroupByCode as $code => $subItems) {
            //采购订单主表
            $purchaseOrder = [];
            $order_sn_code = SnCode::getSnCode('PO_');
            $purchaseOrder['cpid'] = $salerorder['cpid'];
            $purchaseOrder['manger_id'] = $salerorder['purchase_manger_id'];
            $purchaseOrder['order_sn_code'] = $order_sn_code;
            $purchaseOrder['pa_type'] = 4;
            $purchaseOrder['pa_settle_company_name'] = $salerorder['settlement_company'];
            $purchaseOrder['sales_manger_id'] = $manger_id;
            $purchaseOrder['sales_manger_name'] = $salerorder['manger_name'];

            $purchaseOrder['invoice_type'] = $salerorder['bill_type'];
            $purchaseOrder['remark'] = $salerorder['remark'] ?? '';
            $purchaseOrder['is_completion'] = 2;
            $purchaseOrder['is_from_sale'] = 2;
            $purchaseOrder['is_band'] = 2;
            $purchaseOrder['sale_order_number'] = $salerorder['order_number'];
            $purchaseOrder['order_date'] = time();
            $purchaseOrder['create_at'] = time();
            $purchaseOrder['create_manger_id'] = $salerorder['manger_id'];
            $purchaseOrder['sale_sub_ids'] = implode(',',array_column($subItems,'sale_sub_id'));
            $create_purchase_order_id = PurchaseOrder::create($purchaseOrder)->id;

            //采购订单执行主表
            $orderProcess = [];
            $orderProcess['cpid'] = $salerorder['cpid'];
            $orderProcess['manger_id'] = $salerorder['purchase_manger_id'];
            $orderProcess['order_id'] = $create_purchase_order_id;
            $orderProcess['po_order_sn_code'] = $order_sn_code;
            $orderProcess['pa_type'] = 4;
            $orderProcess['sales_manger_id'] = $manger_id;
            $orderProcess['sales_manger_name'] = $manger_name;
            $orderProcess['create_at'] = time();
            $create_purchase_process_order_id = PurchaseOrderProcess::create($orderProcess)->id;
            /***
             *  添加采购订单子表
             *  采购订单执行子表
             *
             */
            foreach ($subItems as $subItem) {
                unset($subItem['code']);
                $subItem['order_id'] = $create_purchase_order_id;

                $create_purchase_order_sub_id = PurchaseOrderSub::create($subItem)->id;

                $purchase_process_sub = $subItem;
                $purchase_process_sub['sub_order_id'] = $create_purchase_order_sub_id;
                $purchase_process_sub['process_order_id'] = $create_purchase_process_order_id;

                PurchaseOrderProcessSub::create($purchase_process_sub);
            }
        }

        return true;
    }

    /***
     * 计提计算公式
     * 正常订单
     * 销售业务计提=销售单价-销售费用单价总和(其他费用之和)-指导价+库存产品计提加成(在系统管理原管理员端计提管理下边的库存
     * 产品计提加成);  指导价= 基价+加价，如果 加价取 发货日期，发货单（带入加价重新计算）更新计提、业绩
     *
     * 自采订单
     *  销售业务计提=销售单价-销售费用单价总和(其他费用之和)-计提底价，(计提底价=自采采购价+自采计提扣减成本(在系统管理原
     *  管理员端计提管理下边的自采计提扣减成本) 自采采购价=采购基价+加价
     *
     * 业绩计算公式
     * 业绩=计提*吨数+差额。 差额：统审端-销售发货单（子订单），填写 采购订单差额
     * 计提单位（分），差额单位（分）
     * 2025.04.25 王丹娜
     *
     */
    public function getaccrualperformance(Request $request)
    {

        $res = (new \App\Services\SaleOrder\SaleOrder())->getaccrualperformance($request->all(), $this->mangerinfo);

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $res]);
    }

    /***
     *  常规订单，计提 业绩
     *  销售业务计提=销售单价-销售费用单价总和(其他费用之和)-指导价+库存产品计提加成(在系统管理原管理员端计提管理下边的库存
     *  产品计提加成);  指导价= 基价+加价，如果 加价取 发货日期，发货单（带入加价重新计算）更新计提、业绩
     *
     *
     */
    public function accrual_in_normal_purchase($cpid = 0, $unit_price = 0, $otherfee_total = 0, $guiding_price = 0)
    {
        //库存产品计提加成
        $companycosts = 0;
        $costs = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'company_costs'])->value('value');
        if ($costs) {
            $companycosts = mathfuncmoney('mul', $costs, 100, 2);
        }

        $res_money = mathfunc('sub', $unit_price, $otherfee_total, 2);
        $res_money = mathfunc('sub', $res_money, $guiding_price, 2);
        $res_money = mathfunc('add', $res_money, $companycosts, 2);


        return $res_money;
    }

    /***
     *
     * 业绩计算公式
     *  业绩=计提*吨数+差额。 差额：统审端-销售发货单（子订单），填写 采购订单差额
     *  $accrual $diff 分
     *  $total_weight g
     *
     */
    public function performance($accrual = 0, $total_weight = 0, $diff = 0)
    {
        $performance = mathfunc('mul', $accrual, $total_weight, 2);
        $performance = mathfunc('div', $performance, 10000, 2);

        $performance = mathfunc('add', $performance, $diff);
        return $performance;
    }

    /***
     *  自采订单，计提 业绩
     *  销售业务计提=销售单价-销售费用单价总和(其他费用之和)-计提底价，(计提底价=自采采购价+自采计提扣减成本(在系统管理原
     *  管理员端计提管理下边的自采计提扣减成本) 自采采购价=采购基价+加价
     *  自采采购价 = $guiding_price
     *
     */
    public function accrual_in_system_purchase($cpid = 0, $unit_price = 0, $otherfee_total = 0, $guiding_price = 0)
    {
        //自采计提扣减成本
        $sys_purchase_company_costs = 0;
        $costs = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'sys_purchase_company_costs'])->value('value');
        if ($costs) {
            $sys_purchase_company_costs = mathfuncmoney('mul', $costs, 100, 2);

        }

        $res_money = mathfunc('sub', $unit_price, $otherfee_total, 2);
        $res_money = mathfunc('sub', $res_money, $guiding_price, 2);
        $res_money = mathfunc('sub', $res_money, $sys_purchase_company_costs, 2);

        return $res_money;
    }


    public function getaccrualsysp($cpid, $sale_sub_id, $purchase_price)
    {
        // $sale_sub_id = $request->sale_sub_id ?? 0;
        // if ($sale_sub_id == 0) {
        //     return;
        // }

        // $purchase_price = $this->purchase_price ?? 0;

        $one = ModelSaleorderSub::where(['id' => $sale_sub_id])->first()->toArray();
        $p = ModelSaleorder::where(['id' => $one['p_id']])->first()->toArray();
        $sys_purchase_company_costs = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'sys_purchase_company_costs'])->first();
        if ($sys_purchase_company_costs) {
            $sys_purchase_company_costs = $sys_purchase_company_costs->value;
            $sys_purchase_company_costs = mathfuncmoney('mul',$sys_purchase_company_costs,100,2);
        } else {
            $sys_purchase_company_costs = 0;
        }
        $salefeeprice = ModelSaleOrderFee::where(['order_number' => $p['order_number']])->get()->sum('price');
        $accrual = $one['unit_price'] - $salefeeprice - ($purchase_price + $sys_purchase_company_costs);
        $performance = mathfuncweight('div', ($accrual * $one['total_weight']), 10000, 2);
        ModelSaleorderSub::where(['id' => $sale_sub_id])->update(['accrual' => $accrual, 'performance' => $performance]);
        return true;
    }

    /***
     *  获取当前订单是否允许发货, 订单状态是否审核中
     *
     *
     */
    public function getsaleorderstatus(Request $request)
    {
        $id = $request->id;
        $subIds = $request->subIds ?? '';
        /***
         * $subIds 参数，是为了返回子订单，根据 基价、加价规则，返回正确的单价。2025.05.15
         *
         */
        if (empty($id) || empty($subIds)) {
            return $this->response()->json(["code" => "001", "msg" => "销售订单id不能为空", "data" => false]);
        }
        $suborder_ids = explode(',', $subIds);
        $res = $this->SaleOrderAuditStatus($id, 'sale_order_delivery',$suborder_ids);
        return response()->json($res);
    }

    /**
     *  获取销售订单状态，是否审核中
     *
     *  节点，销售订单 修改/发货状态，
     *  sale_order_edit/sale_order_deliverys
     *
     */
    public function SaleOrderAuditStatus($id = 0, $node = 'sale_order_edit',$suborder_ids = 0)
    {
        $res = ['code' => '001', 'data' => false];
        $id = intval($id);
        if ($id <= 0) {
            $res['msg'] = '数据异常';
            return $res;
        }
        /**
         *  检测当前场景是否合法
         *
         */
        if (!in_array($node, array_keys(self::$saleOrderNode))) {
            if ($id <= 0) {
                $res['msg'] = $node . ',请求异常';
                return $res;
            }
        }

        $SaleOrder = ModelSaleorder::where('id', $id)->first();
        if (in_array($SaleOrder['del_status'], [2, 3])) {
            if ($SaleOrder['del_status'] == 2) {
                $res['msg'] = '订单删除审核中，不能操作';
                return $res;
            }
            if ($SaleOrder['del_status'] == 3) {
                $res['msg'] = '订单已删除，不能操作';
                return $res;
            }
        }
        if ($SaleOrder['examine_status'] == 2 || $SaleOrder['order_status'] == 2) {
            $res['msg'] = '订单审核中，不能操作';
            return $res;
        }
//        if ($SaleOrder['examine_status'] == 2) {
//            $res['msg'] = '低于指导价审核中，不能操作';
//            return $res;
//        }
//        if($SaleOrder['order_status'] == 2) {
//            $res['msg'] = '订单未审核，请稍等！';
//            return $res;
//        }
        if ($SaleOrder['examine_status'] == 4 || $SaleOrder['order_status'] == 4) {
            $res['msg'] = '审核被驳回，不能操作';
            return $res;
        }
        /**
         *  发货场景前，进行状态检测
         *
         */
        if ($node == 'sale_order_delivery') {
            if ($SaleOrder['is_sys_purchase'] == 2) {
                if(empty($suborder_ids))
                {
                    $purchaseOrder = PurchaseOrder::where('sale_order_number', $SaleOrder['order_number'])
                        ->where('is_finish', 1)
                        ->first();
                    if ($purchaseOrder) {
                        $res['msg'] = '自采订单没有完成采购流程，请稍等！';
                        return $res;
                    }
                }else{
                    $purchaseOrder = PurchaseOrder::where(function ($query) use ($suborder_ids) {
                            foreach ($suborder_ids as $id) {
                                $query->orWhereRaw("FIND_IN_SET(?, sale_sub_ids)", [$id]);
                            }
                        })
                        ->where('is_finish', 1)
                        ->first();
                    if ($purchaseOrder) {
                        $res['msg'] = '自采订单没有完成采购流程，请稍等！';
                        return $res;
                    }

                }

            }
        }
        /***
         *
         *  销售订单编辑场景
         *
         */
        if ($node == 'sale_order_edit') {
            if ($SaleOrder['produce_status'] != '1') {
                $res['msg'] = '生成中/已生成销售订单，不可修改！';
                return $res;
            }
        }
        $res['code'] = '000';
        $res['data'] = true;
        return $res;
    }

    /**
     *  获取账套, 销售订单是否超重
     *
     *
     */
    public function checkSaleOrderOverWeight($cpid, $total_weight = 0)
    {
        $res = ['code' => '001'];
        if (!$cpid) {
            $res['msg'] = "cpid 不能为空";
            return $res;
        }
        $saleprice = ModelSaleprice::where(['cpid' => $cpid, 'type' => 'base', 'is_del' => 1])->first();
        if (!$saleprice) {
            $res['code'] = "000";
            return $res;
        }
        $saleprice = $saleprice->toArray();
        $limit_weight = $saleprice['limit_weight'] ?? 0;
        /**
         *  统计销售订单，除过 已删除订单。
         *  1.销售订单限制重量统计，统计发布限重日期后的
         *
         */
        $exist_sale_order_weight = ModelSaleordersub::where(['cpid' => $cpid, 'is_del' => config('constants.is_del.no')])
            ->where('create_at', '>=', $saleprice['create_at'])
            ->sum('total_weight');
        $target_weight = $total_weight + $exist_sale_order_weight;
        if ($limit_weight < $total_weight || $limit_weight < $target_weight) {
            $res['data'] = $limit_weight;
            $res['msg'] = "超出限重:" . mathfuncweight('div', $limit_weight ?? 0, 10000, 4) . '吨';
            return $res;
        }
        $res['code'] = '000';
        return $res;
    }

    /**
     *  订单创建场景
     *
     *  低于指导价逻辑段 2025.04.23
     *  $unit_price     钢材单价 (分)
     *  $guiding_price  钢材指导价 单位(分)
     *  $preferential_price 优惠客户优惠的金额 单位(分)
     *  $is_sys_purchase 已销定采标识
     *
     */
    public function checkLowGuidePrice($data = [], $custom = [], $operate = 'add', $unit_price = 0, $guiding_price = 0, $preferential_price = 0, $is_sys_purchase = 0, $otherfeetotal = 0)
    {
        $res = ['code' => '001', 'msg' => ''];
        $res['data']['sub_examine_status'] = config('constants.examine_status.normal');
        /**
         *
         *
         *  新增时
         *  常规类型/锁量不锁规格/保价
         *  销售订单的创建：优惠客户销售时用单价-其他费用之和-指导价<0
         *  需要产品经理审批(低于指导价审核)，普通客户不允许创建订单，目前的判断和其他费用无关.2025.04.11
         *  满足上述判断条件的 优惠客户审核，普通客户禁止创建订单
         *
         *  order_type 销售订单类型，1常规类型，2锁量不锁规格，3保价订单，4点价
         *  custom_level 客户价等级，1普通客户，2优惠客户
         *
         */
        if ($data['order_type'] == '1' || $data['order_type'] == '3') {
            if ($custom['custom_level'] == '1') {
                if ($unit_price < $guiding_price) {
                    $res['msg'] = '单价不能低于指导价';
                    return $res;
                }
                if ($unit_price - $guiding_price - $otherfeetotal < 0) {
                    $res['msg'] = '单价低于指导价，无法创建订单！';
                    return $res;
                }
            }
            if ($custom['custom_level'] == 2) {
//                if ($unit_price < $guiding_price) {
//                    $res['code'] = '000';
//                    $res['data']['sub_examine_status'] = config('constants.examine_status.in_review');
//                    return $res;
//                }
//                if (($unit_price + $preferential_price) < $guiding_price) {
//                    //进入审核
//                    $res['code'] = '000';
//                    $res['data']['sub_examine_status'] = config('constants.examine_status.in_review');
//                    return $res;
//                }
                if ($unit_price - $guiding_price - $otherfeetotal < 0) {
                    //进入审核
                    $res['code'] = '000';
                    $res['data']['sub_examine_status'] = config('constants.examine_status.in_review');
                    return $res;
                }
            }
            $res['code'] = '000';
            return $res;
        }
        if ($data['order_type'] == '2') {
            /***
             * 锁量不锁规格的订单
             * 价格按照创建订单的基价计算，单价不低于基价(基价+加价)，金额=重量*单价，这里的计提和业绩按照没有加价来计算
             * 否则拦截
             */
//            if ($is_sys_purchase == '2') {
//                $res['msg'] = '订单不能自采';
//                return $res;
//            }
            if ($unit_price < $guiding_price) {
                $res['msg'] = '单价低于指导价，无法创建订单！';
                return $res;
            }
            $res['code'] = '000';
//            $res['data']['sub_examine_status'] = config('constants.examine_status.in_review');
            return $res;
        }
        if ($data['order_type'] == '4') {
//            if ($is_sys_purchase == '2') {
//                $res['msg'] = '订单不能自采';
//                return $res;
//            }
            $res['code'] = '000';
            return $res;
        }
        return $res;
    }

    /***
     * 订单审核 新增/修改场景
     * 检测订单是否需要审核
     *
     */
    public function checkOrderReview($data = [], $operate = 'add')
    {
        $res = ['code' => '001', 'msg' => ''];
        if ($data['order_type'] == '1') {
            $res['code'] = '000';
            if ($operate == 'add') {
                $res['data']['order_status'] = config('constants.order_status.audit');
            }
            if ($operate == 'edit') {
                $res['data']['order_status'] = config('constants.order_status.in_review');
            }

            return $res;
        }
        if ($data['order_type'] == '2' || $data['order_type'] == '4') {
//            if ($is_sys_purchase == '2') {
//                $res['msg'] = '订单不能自采';
//                return $res;
//            }
            $res['code'] = '000';
            $res['data']['order_status'] = config('constants.order_status.in_review');
            return $res;
        }
        if ($data['order_type'] == '3') {
            $res['code'] = '000';
            $res['data']['order_status'] = config('constants.order_status.in_review');
            return $res;
        }
        return $res;
    }

    /**
     *  检测子订单数据是否符合规则
     *
     *  常规订单 重量/金额/件数
     *
     *  锁量不锁规格（只有这个能选择虚拟）  重量>0 不扣库存 件数 可输可不输 金额必须大于0
     *
     *  保价订单，价格只能比创建的低 不能变高
     *
     *  点价 扣库存 不扣钱， 结算单扣钱。 重量、金额、件数 都正常
     *
     *  total_weight
     *  unit_price 单价(单位：分)
     *  pieces
     */
    public function checkSubOrderItem($node = 'SaleOrder', $data = [], $item = [], $total_weight = 0, $unit_price = 0, $pieces = 0)
    {
        $res = ['code' => '001', 'msg' => ''];
        /***
         *  已销定采订单，子订单重量
         *  库存可用重/库存件数
         *
         *
         */
        //非自采订单 生效
        if (isset($item['is_sys_purchase']) && $item['is_sys_purchase'] == '1') {
            if ($total_weight <= 0) {
                $res['msg'] = '重量必须大于0';
                return $res;
            }
        }
        //自采
        if (isset($item['is_sys_purchase']) && $item['is_sys_purchase'] == '2') {
            if ($total_weight < 0) {
                $res['msg'] = '重量必须大于等于0';
                return $res;
            }
        }
        if ($unit_price <= 0) {
            $res['msg'] = '单价必须大于0';
            return $res;
        }
        //非自采订单 生效
        if (isset($item['is_sys_purchase']) && $item['is_sys_purchase'] == '1') {
            if (isset($item['total'])) {
                $total = mathfuncmoney('mul', $item['total'], 100, 2);
                if ($total <= 0) {
                    $res['msg'] = '金额必须大于0';
                    return $res;
                }
            }
        }
        if ($node == 'SalesOrder') {
            if ($pieces <= 0) {
                $res['msg'] = '件数必须大于0';
                return $res;
            }
        }
        if ($node == 'SaleOrder') {
            //常规订单，保价订单
            if (in_array($data['order_type'], ['1', '3', '4'])) {
                if ($pieces <= 0) {
                    $res['msg'] = '件数必须大于0';
                    return $res;
                }
            }
            /***
             *
             * 锁量不锁规格订单，子订单钢材必须是虚拟
             *
             *
             */
            if ($data['order_type'] == '2') {
                if (isset($pieces) && $pieces < 0) {
                    $res['msg'] = '件数必须大于等于0';
                    return $res;
                }
                if (isset($item['archive_type']) && $item['archive_type'] != '4') {
                    $res['msg'] = '锁量不锁规格，子订单必须是虚拟钢材';
                    return $res;
                }
            }
        }
        $res['code'] = '000';
        return $res;
    }

    /***
     *
     * 修改销售订单/销货单，返还/扣除 库存操作 2025.04.25
     *
     * 加库存 total_weight 数据库值,直接加减  单位:(100g)
     *
     * 减库存 total_weight 前端传入值，需要转换  单位:吨
     *
     * total_weight_unit 单位 吨/g
     *
     * 已销定采，扣库存；第一次创建销售订单(扣库存)，销售到采购。
     * 采购（业务自采），修改后 （返上次库存，重新扣库存），可以多次修改。数据绑定合同后，无法修改，扣库存操作完成。
     *
     *
     * 销售订单/销售发货单库存逻辑； 以下逻辑存疑，需要在确认 2025.06.28
     * 第一次销售订单创建，已经加已锁，减可用。发货时超发(实际上常规订单不可超发)，不锁直接扣可用。
     * 第二次原订单发货，加已锁，减可用。。以此类推
     *
     * 虚拟订单，创建订单时不扣库存。发货单创建时，扣库存。2025.07.08
     *
     */
    public function incrDecrStockInSaleEdit($orderList = [], $operate = 'incr', $total_weight_unit = 'ton')
    {
        $res = ['code' => '000', 'msg' => ''];
//        if($item['archive_type']!=4){
//            Stock::where(['id' => $item['stock_id']])->update([
//                'can_use_pieces' => DB::raw('can_use_pieces - ' . $item['pieces']),
//                'can_use_weight' => DB::raw('can_use_weight - ' . $item['total_weight']),
//                'locked_pieces' => DB::raw('locked_pieces + ' . $item['pieces']),
//                'locked_weight' => DB::raw('locked_weight + ' . $item['total_weight']),
//            ]);
//        }
        if (!empty($orderList)) {
            foreach ($orderList as $item) {
                if ($item['pieces'] < 0 || $item['total_weight'] < 0) {
                    $res['code'] = '001';
                    $res['msg'] = "库存增减失败，子订单件数和重量不小于0";
                    break;
                }
                //虚拟钢材不扣库存
                if (isset($item['archive_type']) && $item['archive_type'] == '4') {
                    continue;
                }
                if ($total_weight_unit == 'ton') {
                    $item['total_weight'] = mathfuncweight('mul', $item['total_weight'], 10000, 4);
                }
                if ($operate == 'incr') {
                    Stock::where(['id' => $item['stock_id']])->update([
                        'can_use_pieces' => DB::raw('can_use_pieces + ' . $item['pieces']),
                        'can_use_weight' => DB::raw('can_use_weight + ' . $item['total_weight']),
                        'locked_pieces' => DB::raw('locked_pieces - ' . $item['pieces']),
                        'locked_weight' => DB::raw('locked_weight - ' . $item['total_weight']),
                    ]);
                }
                if ($operate == 'decr') {
                    Stock::where(['id' => $item['stock_id']])->update([
                        'can_use_pieces' => DB::raw('can_use_pieces - ' . $item['pieces']),
                        'can_use_weight' => DB::raw('can_use_weight - ' . $item['total_weight']),
                        'locked_pieces' => DB::raw('locked_pieces + ' . $item['pieces']),
                        'locked_weight' => DB::raw('locked_weight + ' . $item['total_weight']),
                    ]);
                }
            }
        }
        return $res;
    }

    /***
     *  销售出库,扣库存
     *  不为0，减去数量值，=0 删除子库存
     *
     *
     *
     */
    public function outboundDecrStockInSale($orderList = [], $operate = 'decr', $total_weight_unit = 'ton')
    {
        $res = ['code' => '000', 'msg' => ''];
        if (!empty($orderList)) {
            foreach ($orderList as $item) {
                if ($item['pieces'] <= 0 || $item['weight'] <= 0) {
                    $res['code'] = '001';
                    $res['msg'] = "库存增减失败，子订单件数和重量必须大于0";
                    break;
                }
                //虚拟钢材不扣库存
                if (isset($item['archive_type']) && $item['archive_type'] == '4') {
                    continue;
                }
                if ($total_weight_unit == 'ton') {
                    $item['weight'] = mathfuncweight('mul', $item['weight'], 10000, 4);
                }
                /****
                 * 扣子库存，目前 销售订单创建后，发货时 可发多于订单的件数
                 * 已锁 < 发货量，已锁扣完，从现存量扣，针对父库存.已锁不能为负数
                 * 都不足时，报错，2025.06.23
                 *
                 *  ModelStock 模型查库存，返回的重量属性 都/10了，历史遗留问题。需要*10 还原为g
                 *
                */
//                ModelStock::where(['id' => $item['stock_id']])->update([
//                    'locked_pieces' => DB::raw('locked_pieces - ' . $item['pieces']),
//                    'locked_weight' => DB::raw('locked_weight - ' . $item['weight']),
//                    'current_pieces' => DB::raw('current_pieces - ' . $item['pieces']),
//                    'current_weight' => DB::raw('current_weight - ' . $item['weight']),
//                ]);
                $update_locked_pieces = 0;
                $update_locked_weight = 0;
                $update_current_pieces = 0;
                $update_current_weight = 0;
                $ModelStock = ModelStock::where(['id' => $item['stock_id']])->first();

                $ModelStock_locked_weight = mathfuncweight('mul',$ModelStock['locked_weight'],10,0);
                $ModelStock_current_weight = mathfuncweight('mul',$ModelStock['current_weight'],10,0);

                if($item['pieces'] <= $ModelStock['locked_pieces']){
                    $update_locked_pieces = mathfunc('sub',$ModelStock['locked_pieces'],$item['pieces'],0);
                    $update_current_pieces = mathfunc('sub',$ModelStock['current_pieces'],$item['pieces'],0);
                }else{
                    $excess_pieces = mathfunc('sub',$item['pieces'],$ModelStock['locked_pieces'],0);
                    $decr_current_pieces = mathfunc('add',$item['pieces'],$excess_pieces,0);
                    $update_current_pieces = mathfunc('sub',$ModelStock['current_pieces'],$decr_current_pieces,0);
                }

                if($item['weight'] <= $ModelStock_locked_weight){
                    $update_locked_weight = mathfunc('sub',$ModelStock_locked_weight,$item['weight'],0);
                    $update_current_weight = mathfunc('sub',$ModelStock_current_weight,$item['weight'],0);

                }else{
                    $excess_weight = mathfunc('sub',$item['weight'],$ModelStock_locked_weight,0);
                    $decr_current_weight = mathfunc('add',$item['weight'],$excess_weight,0);
                    $update_current_weight = mathfunc('sub',$ModelStock_current_weight,$decr_current_weight,0);
                }
//                if($update_current_pieces < 0 || $update_current_weight < 0){
//                    $res['code'] = '001';
//                    $res['msg'] = "扣库存失败。库存不足,无法出库";
//                    break;
//                }

                ModelStock::where(['id' => $item['stock_id']])->update([
                    'locked_pieces' => $update_locked_pieces,
                    'locked_weight' => $update_locked_weight,
                    'current_pieces' => $update_current_pieces,
                    'current_weight' => $update_current_weight,
                ]);

                /***
                 * 子库存  扣减 总重、件数
                 *
                 */
                if (!empty($item['suborder'])) {
                    foreach ($item['suborder'] as $subitem) {
                        $subitem['total_weight'] = mathfuncweight('mul', $subitem['total_weight'], 10, 0);
                        $stockSub = StockSub::where('id', $subitem['id'])->first();
                        $stockSub_total_weight = mathfuncweight('mul', $stockSub['total_weight'], 10, 0);
                        if ($stockSub['can_use_pieces'] > $subitem['pieces']) {
                            StockSub::where(['id' => $subitem['id']])->update([
                                /***
                                 *  子库存可用件，对应 子库存件数
                                 *  子库存总重，对应子库存 总重  2025.05.16
                                 *
                                 *  suborder孙库存 total_weight 采购入库来的单位，222.2 实际 要*10=数据库子库存真实重量
                                 *
                                 */
                                'can_use_pieces' => DB::raw('can_use_pieces - ' . $subitem['pieces']),
                                'total_weight' => DB::raw('total_weight - ' . $subitem['total_weight']),

                            ]);
                        }
                        /***
                         * 库存耗尽，删除子库存
                         * 判定删除子库存
                         * 件数和重量为0，删除子库存 2025.05.16
                         * $stockSub['total_weight'] *10
                         *
                         * && $stockSub_total_weight == $subitem['weight']
                         *
                         */
                        if ($stockSub['can_use_pieces'] == $subitem['pieces']) {
                            StockSub::where('id', $subitem['id'])->delete();
                        }
                        if($stockSub['can_use_pieces'] < $subitem['pieces']){
                            $res['code'] = '001';
                            $res['msg'] = "库存增减失败，子库存不足";
                            break;
                        }
                    }
                }
            }
        }
        return $res;
    }

    public static function amountTransformIntoCent($amount = 0)
    {
        return mathfuncmoney('mul', $amount, 100, 2);
    }

    public static function amountTransformIntoYuan($amount = 0)
    {
        return mathfuncmoney('div', $amount, 100, 2);
    }

    public static function weightTransformIntoG($weight = 0)
    {
        return mathfuncmoney('mul', $weight, 10000, 2);
    }

    public static function weightTransformIntoTon($weight = 0)
    {
        return mathfuncmoney('div', $weight, 10000, 2);
    }

    /***
     * 获取 自采订单，指导价
     * 通过销售子订单 直接查询 采购子订单
     *
     *
     */
    public function getSystemPurchaseGuidingPrice($sales_sub_id = 0)
    {
        $PurchaseOrderSub = PurchaseOrderSub::where('sale_sub_id', $sales_sub_id)->first();
        if (!$PurchaseOrderSub) {
            return 0;
        }
        $guiding_price = mathfunc('add', $PurchaseOrderSub['base_price'], $PurchaseOrderSub['add_price']);
        return $guiding_price;
    }
    /****
     *  销售订单号，有可能重复。增加一层验证，暂时不改 销售订单号
     *  2025.06.30
     *
     *
    */
    public function buildSaleOrderNumber($cpid = 0,$max_attempts = 5){
        $res = ['code' => '001','msg' => ''];
        if(empty($cpid)){
            $res['msg'] = '账套不能为空';
            return $res;
        }
        for($attempts=1;$attempts <=$max_attempts;$attempts++){
            $order_number = getRandomString();
            $ModelSaleorder = ModelSaleorder::where(['cpid'=>$cpid,'order_number' =>$order_number,'is_del' => 1])->first();
            if(!$ModelSaleorder){
                $res['code'] = '000';
                $res['order_number'] = $order_number;
                return $res;
            }
        }
        $res['msg'] = "生成唯一订单号失败，已尝试 ".$max_attempts." 次";
        return $res;
    }
}
